java find all char occurences code example
Example 1: count occurrences of character in string java 8
String someString = "elephant";
long count = someString.chars().filter(ch -> ch == 'e').count();
assertEquals(2, count);
long count2 = someString.codePoints().filter(ch -> ch == 'e').count();
assertEquals(2, count2);
Example 2: number of occurence string in java
public class StringNumberOfOccurenceLetter {
private static int countOccurences(String word, char character){
int count = 0;
for (int i = 0; i < word.length() ; i++) {
if (word.charAt(i)==character){
count++;
}
}
return count;
}
public static void main(String[] args) {
int count = countOccurences("dddssad", 'a');
}
}