Simple way to count character occurrences in a string
To count the occurrences of a character in a string in Java, you can use the charAt()
method of the String
class to iterate over the characters in the string and check if each character is equal to the target character.
Here is an example of how to do this:
String str = "Hello World!";
char ch = 'l';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
System.out.println("Number of occurrences of '" + ch + "': " + count);
In this example, the charAt()
method is used to get the character at each index of the string, and the if
statement is used to check if the character is equal to the target character. If the characters are equal, the count
variable is incremented. At the end, the count
variable contains the number of occurrences of the character in the string.
You can also use the String.replace()
method to replace all occurrences of the character with an empty string and then use the length()
method to get the number of characters that were removed:
String str = "Hello World!";
char ch = 'l';
int count = str.length() - str.replace("l", "").length();
System.out.println("Number of occurrences of '" + ch + "': " + count);
I hope this helps. Let me know if you have any questions.