Count the occurrence of chars in a given string



In this article, we will check the occurrence of a given character in a string
For this, we traverse the string in a loop visiting each character and increase the count by 1 if the given character is present.

 

Iterative Approach

  1. Initialise count as zero
  2. Traverse the whole string and check the given character is present then increase count by 1 and move further
  3. Print the occurrence of a given character in the string
Iterative Complexity

Time Complexity: O(N) where n is the length of the string
Space Complexity: O(1)

 

Recursive Approach

  1. If length of string is zero then return 0
  2. If the character at the 0th position in the string is equal to the given character,then increase count by 1
  3. And call function again by passing character and next position in string
  4. Return the count after traversing the string is completed
Recursive Complexity

Time Complexity: O(N) where n is the length of the string
Space Complexity: O(N) for the recursive call stack

 

Java Code
class CountCharacter {

    public int countOcurrIterative(String s, char c) {
        int count = 0;

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == c)
                count++;
        }
        return count;
    }

    public int countOcurrRecursive(String s, char c) {
        if (s.length() == 0)
            return 0;

        int count = 0;
        if (s.charAt(0) == c)
            count++;
        count += countOcurrRecursive(s.substring(1), c);

        return count;
    }

    public static void main(String args[]) {
        String str = "banana";
        char ch = 'a';

        CountCharacter countchar = new CountCharacter();

        System.out.println("Given String is :" + str);

        System.out.println("Using Iterative Approach ");
        System.out.println("Occurrence of characters " + ch + " is " + countchar.countOcurrIterative(str, ch));

        System.out.println("Using Recursive Approach ");
        System.out.println("Occurrence of characters " + ch + " is " + countchar.countOcurrRecursive(str, ch));

    }

}
 
Output

Given String is banana
Using Iterative Approach
Occurrence of characters a is 3
Using Recursive Approach
Occurrence of characters a is 3



Thanks for feedback.



Read More....
Check if a string is a valid palindrome
Check if two strings are anagram of each other
Find duplicate chars in a String
First non-repeating character in String
Reverse a string