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
- Initialise count as zero
- Traverse the whole string and check the given character is present then increase count by 1 and move further
- 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
- If length of string is zero then return 0
- If the character at the 0th position in the string is equal to the given character,then increase count by 1
- And call function again by passing character and next position in string
- 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.