java

Java – Count Occurrences of a Char in a String

In this tutorial, we are going to see how to count the number of occurrences of a Char in a String in Java.

In the code below, we count the number of occurrences of each character in a string. To do this, we first create an array of size 256, the idea here is to store the number of occurrences relative to the ASCII value of that character. For example, the occurrence of “A” would be stored as [65] because the ASCII value of A is 65.
 

 

How to Count Occurrences of a Char in a String in Java
public class Main {   
    static void countOccurrence(String text) 
    {
        int count[] = new int[256]; 
  
        int len = text.length(); 
  
        // Initialize the index of the count array
        for (int i = 0; i < len; i++) 
            count[text.charAt(i)]++; 
 
        char ch[] = new char[text.length()]; 
        for (int i = 0; i < len; i++) { 
            ch[i] = text.charAt(i); 
            int occurrence = 0; 
            for (int j = 0; j <= i; j++) { 
                // Check if matches were found
                if (text.charAt(i) == ch[j])
                    occurrence++;                 
            } 

            if (occurrence == 1)  
                System.out.println("The Number of occurrences of " + 
                 text.charAt(i) + " is:" + count[text.charAt(i)]);             
        } 
    }
    public static void main(String[] args) 
    { 
        String text = "StackHowTo"; 
        countOccurrence(text); 
    } 
}

Output:

The Number of occurrences of S is: 1
The number of occurrences of t is: 1
The Number of occurrences of a is: 1
The Number of occurrences of c is: 1
The Number of occurrences of k is: 1
The Number of occurrences of H is: 1
The Number of occurrences of o is: 2
The Number of occurrences of w is: 1
The Number of occurrences of T is: 1
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *