How to Count Occurrence of a given Character in a String in Java ?

  • The number of occurrences of each character to be count and also the occurrences of duplicate characters it should not be display repeatedly. The following steps are given below,
    • First, we split the strings by spaces.
    • Take a variable count = 0 and in every true condition we increment the count by 1.
    • Now run a loop at 0 to length of string.
    • And then check if our string is equal to the word.
    • If condition true then we increment the value of count by 1.

Sample Code in Java

class wiki{
public static void main (String[] args) {
String str = "Welcome to wikitechy website. Wikitechy is the best website to learn technology."
String findStr = "wikitechy";
int lastIndex = 0;
int count = 0;

while(lastIndex != -1){

lastIndex = str.indexOf(findStr,lastIndex);

if(lastIndex != -1){
count ++;
lastIndex += findStr.length();
}
}
System.out.println(count);
}
}

Output

2

Categorized in:

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,