String Based
Counting
Base Code
void count(String str) {
int count = 0;
char ch;
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if ({condition here}) {
count++; // or count = count + 1
}
}
System.out.println(count);
}
Pick & Concatenate (Join)
Here, we'll pick a character if it satisfies a particular condition and add it to another string which will be printed out later.
Base Code
void pickAndConcat(String str) {
String s = "";
char ch;
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if ({condition here}) {
s += ch;
}
}
System.out.println(s);
}
Pick & Remove (Join)
Here, we'll pick a character if it satisfies a particular condition. If it does not, then it is added to another string else not.
Base Code
void pickAndConcat(String str) {
String s = "";
char ch;
for (int i = 0; i < str.length(); i++) {
ch = str.charAt(i);
if (!{condition here}) {
s += ch;
}
}
System.out.println(s);
}
Here we've used the ! (not) operator which basically flips the boolean.
The Conditions
You'll have to substitute these conditions in place of {condition here}
- Digits:
Character.isDigit(ch) - Spaces:
ch == ' 'orCharacter.isWhitespace(ch)if you want to include all types of whitespaces. - Vowels:
ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' - Consonants:
(ch != 'a' || ch != 'e' || ch != 'i' || ch != 'o' || ch != 'u') && Character.isLetter(ch)Note:
Character.isLetteris important as the supplied character may not be a letter. - Uppercase:
Character.isUpperCase(ch) - Lowercase:
Character.isLowerCase(ch)
String & ASCII Based
-
Printing character ASCII table. The objective is to print each character of a string along with its corresponding ASCII value.
Solution
void printASCIITable(String s) { for (int i = 0; i < s.length(); i++) { System.out.println(s.charAt(i) + "\t" + (int)(s.charAt(i))); } } -
Total of ASCII values of all characters.
Solution
int totalASCII(String s) { int total = 0; for (int i = 0; i < s.length(); i++) { total += (int)(s.charAt(i)); } return total; } -
Concat odd ASCII Characters
We'll concat all odd ASCII value characters in one new string
Solution
String oddASCIIStr(String s) { String new_string = ""; for (int i = 0; i < s.length(); i++) { if ((int)(s.charAt(i)) % 2 != 0) { new_string += s.charAt(i); } } return new_string; }
First & Last
- Converting the first and last character of an given string to lowercase and others to upper case.
Solution
One liner:String firstLastLower(String str) { String s = Character.toLowerCase(str.charAt(0)); // first lower s += s.substring(1, s.length() - 1).toUpperCase(); // the middle s += Character.toLowerCase(s.charAt(s.length() - 1)); return s; }String firstLastLower(String str) { return Character.toLowerCase(str.charAt(0)) + s.substring(1, s.length() - 1).toUpperCase() + Character.toLowerCase(s.charAt(s.length() - 1)); }Note that this is error-prone as it does not check whether string is empty or not.