There are multiple way to count the number of specific characters in a string java. here we are count the character ‘h’ in the given string.
From toCharArray() and forloop() method:-
- Create test method with int return type.
- Declare a default count variable.
- Convert String to character from str.toCharArray() method and store in ch[] array.
- Iterate the character from for loop 0 to ch.length till.
- Inside if condition, we compare the given character to character array index value.
- If it return true then count and increment.
- Now print the number of character value from i.
From java8 map and filter :-
- First we convert string to intStream from chars() method.
- From mapToObj() method we convert intStream data into Stream<Character>.
- Inside filter we compare given character from input character ch value.
- Now count the character from count() method.
- Print number of character.
public class CountCharDemo {
public static void main(String[] args) {
CountCharDemo cd = new CountCharDemo();
String str = "how are you well here";
// from toCharArray and for loop method
int i = cd.test('h', str);
System.out.println("total number of character from TocharArray :- " + i);
// from java8 map and filter
long count = str.chars().mapToObj(x -> (char) x).filter(ch -> ch == 'h').count();
System.out.println("from java8 map and filter :- " + count);
}
public int test(char c, String str) {
int count = 0;
char ch[] = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (c == ch[i]) {
count++;
}
}
return count;
}
}
Output :-
total number of character from TocharArray :- 2
from java8 map and filter :- 2