Counting and Filtering Chars
Practical char tasks.
Counting With a Loop
To count characters, keep a counter variable and add 1 each time a condition matches.
Start the counter at 0, loop over every char, and increase it when the char passes your test.
int count = 0;
for (char c : "hello".toCharArray()) {
count++;
}Counting Vowels
Here we count vowels by checking each char against the vowel set.
We lowercase the char first so both 'A' and 'a' are counted the same way.
public class Main {
public static void main(String[] args) {
String text = "Java Rocks";
int vowels = 0;
for (char c : text.toCharArray()) {
char low = Character.toLowerCase(c);
if (low == 'a' || low == 'e' || low == 'i' || low == 'o' || low == 'u') {
vowels++;
}
}
System.out.println(vowels);
}
}All lessons in this course
- The char Primitive
- Character Helper Methods
- Looping Over Characters
- Counting and Filtering Chars