There are following ways to count the number of occurrences of a char in a String in Java.
- First we create a noOfOcurrenceCharInString method.
- Pass this method a char and string value parameter.
- Initialize a variable count to read all duplicate character.
- Now convert the string to char array.
- Traverse the all char array value.
- Inside if condition we compare the given character with char array index value character.
- If it is equal then increment the count.
- Now print the count value means the number of occurrences of a character.
public class NoOfGivenDuplicateChar {
public static void main(String[] args) {
int m = NoOfGivenDuplicateChar.noOfOcurrenceCharInString('a', "java is a language");
System.out.println("number of occurance character 'a' is :- " + m);
}
public static int noOfOcurrenceCharInString(char c, String str) {
// TODO Auto-generated method stub
int count = 0;
char[] ch = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (c == ch[i]) {
count++;
}
}
return count;
}
}
Output :-
number of occurance character ‘a’ is :- 5