number of occurrences of a character in a string in java 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: find number of occurrences of a substring in a string java

public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}

Example 3: number of occurrences of character in string

public class CountStringOccurence {
public static void main(String[] args) {

int count= countOccurences("aaassssddadad",'s');
System.out.println(count);

}

private static int countOccurences(String word, char character){
  
  int count = 0;
  for(int i = 0; i < word.length(); i++){
    
    if(word.chartAt(i) == character){
      
      count++; } 
                 }
      return count;
}
}