Learn how to count occurrences of a character in a String in Java using loops. In this tutorial, we will learn how to count the number of times a specific character appears in a string using a simple Java program with an example.
Code Explanation (Step-by-Step)
- create a method named noOfOccurrenceCharInString().
- Pass a character and a String as parameters to the method.
- Initialize a variable count to store the number of occurrences of the given character.
- Convert the String into a character array using the toCharArray()
- Traverse all characters of the array using a for loop .
- Inside the if condition, compare the given character with each character of the array.
- If both characters are equal, increment the count
- After traversing the entire array, return the count
- Now print the count, which represents the number of occurrences of the given character in the String.
public class NoOfGivenDuplicateChar {
public static void main(String[] args) {
int count = noOfOccurrenceCharInString('a', "java is a language");
System.out.println("Number of occurrence of character 'a' is : " + count);
}
public static int noOfOccurrenceCharInString(char ch, String str) {
int count = 0;
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (ch == charArray[i]) {
count++;
}
}
return count;
}
}
`
Output :-
Number of occurrence of character ‘a’ is : 5
Count Occurrences of a Character in a String Using Java 8 Streams
public class CountCharJava8 {
public static void main(String[] args) {
String str = "java is a language";
char ch = 'a';
long count = str.chars()
.filter(c -> c == ch)
.count();
System.out.println("Number of occurrences of 'a' is : " + count);
}
}
Output :-
Number of occurrence of character ‘a’ is : 5
Here are some Java-related programs that will help you understand Java concepts better: