How to count the number of occurrences of a char in a String with Java

5 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "abcdabaamnoa";
        
        int char_count = s.length() - s.replace("a", "").length();
 
        System.out.println(char_count);
    }

}



 
/*
run:
        
5
    
*/

 



answered Sep 11, 2016 by avibootz
edited Oct 10, 2023 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "abcdabaamnoa";
        
        int char_count = s.replaceAll("[^a]", "").length();
 
        System.out.println(char_count);
    }

}



 
/*
run:
        
5
    
*/

 



answered Sep 11, 2016 by avibootz
edited Oct 10, 2023 by avibootz
0 votes
public class MyClass
{
    private static long CountOccurrences(String str, char ch) {
        return str.chars()
                    .filter(c -> c == ch)
                    .count();
    }
 
    public static void main(String[] args)
    {
        String str = "java c dart rust javascript";
  
        System.out.println(CountOccurrences(str, 'a'));
    }
}
  
  
  
  
  
/*
run:
   
5
   
*/

 



answered Oct 10, 2023 by avibootz
0 votes
ublic class MyClass
{
    private static long CountOccurrences(String str, char ch) {
        int counter = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ch) {
                counter++;
            }
        }
  
        return counter;
    }
     
    public static void main(String[] args)
    {
        String str = "java c dart rust javascript";
  
        System.out.println(CountOccurrences(str, 'a'));
    }
}
  
  
  
  
  
/*
run:
   
5
   
*/

 



answered Oct 10, 2023 by avibootz
0 votes
public class MyClass
{
    private static long CountOccurrences(String str, char ch) {
        return str.length() - str.replace(String.valueOf(ch), "").length();
    }
     
    public static void main(String[] args)
    {
        String str = "java c dart rust javascript";
  
        System.out.println(CountOccurrences(str, 'a'));
    }
}
  
  
  
  
  
/*
run:
   
5
   
*/

 



answered Oct 10, 2023 by avibootz
...