Thursday 26 November 2015

How to count the number of occurrences of a character in a string in java

Count the number of occurrences of a character in a string is good programming questions . It is ask in colleges and schools mostly. This question also asked in many times in interviews. 

Method 1:

We can count number of occurrences of a character in a string with the help of indexOf() method.

package com.javaproficiency;

public class CountCharOccurance {
public static void main(String[] args) {
String str = "javaproficiencyexamplebyannu";
 
    String findStr = "a";
    int lastIndex = 0;
    int counter = 0;
 
    while (lastIndex != -1) {
 
     lastIndex = str.indexOf(findStr, lastIndex);
 
     if (lastIndex != -1) {
      counter++;
      lastIndex += findStr.length();
 
     }
    }
    System.out.println(counter);
}


}


Output: 

4


Method 2:

In this example we will use charAt() method of string for count number of occurrences of a character in a string .

package com.javaproficiency;

public class CountCharOccurancejava {
public static void main(String[] args) {
String s = "javaproficiencyexamplebyannu";
int counter = 0;
for( int i=0; i<s.length(); i++ ) {
   if( s.charAt(i) == 'a' ) {
       counter++;
   } 
}
System.out.println( counter );
}

}


Output:

4


No comments:

Post a Comment