How to Count Occurrences of a Character in String - Java Programming Exercise Example

Write a program to count the number of occurrences of a character in String is one of the common programming interview questions not just in Java but also in other programming languages like C or C++.  As String in a very popular topic on programming interviews and there are lot of good programming exercise on String like "count number of vowels or consonants in String", "count number of characters in String" , How to reverse String in Java using recursion or without using StringBuffer etc, it becomes extremely important to have solid knowledge of String in Java or any other programming language. Though, this question is mostly used to test candidate's coding ability i.e. whether he can convert logic to code or not.

In Interview, most of the time Interviewer will ask you to write a program without using any API method,  as Java is very rich and it always some kind of nice method to do the job, But it also important to know rich Java and open source libraries for writing production quality code.

Anyway, in this question, we will see both API based and non-API based(except few) ways to count a number of occurrences of a character in String on Java.


Java program to count occurrences of a character in String

How to find number of occurence of character or substring in String in JavaIn this Java program, we will see a couple of ways to count, how many times a particular character is present in String. First, we'll see Spring framework’s StringUtils class and its static method countOccurrenceOf(String, character) which takes a String and character and returns occurrence of character into that String.

After that, we will see Apache commons StringUtils class for counting occurrence of a character in String. Apache commons StringUtils provide countMatches() method which can be used to count the occurrence of one character or substring.

Finally, we will see the most simple way of counting character using standard for loop and Java 5 enhanced for loop. This solution can be extended not just to finding the occurrence of character but also finding occurrences of a substring.

Btw, if you are solving this question as part of your Java interview preparation, you can also check Cracking the Coding Interview, a collection of 189 programming questions and solutions from various programming job interviews. Your perfect companion for developing coding sense required solving these kinds of problems on interviews. 

How to count occurrence of a character in String


Now, let's see the Java program to count number of occurrence of any character on String:

import org.springframework.util.StringUtils;
/**
 * Java program to count the number of occurrence of any character on String.
 * @author Javin Paul
 */

public class CountCharacters {

    public static void main(String args[]) {
         
        String input = "Today is Monday"; //count number of "a" on this String.
     
        //Using Spring framework StringUtils class for finding occurrence of another String
        int count = StringUtils.countOccurrencesOf(input, "a");
     
        System.out.println("count of occurrence of character 'a' on String: " +
                " Today is Monday' using Spring StringUtils " + count);

     
        //Using Apache commons lang StringUtils class
        int number = org.apache.commons.lang.StringUtils.countMatches(input, "a");
        System.out.println("count of character 'a' on String: 'Today is Monday' using commons StringUtils " + number);
     
        //counting occurrence of character with loop
        int charCount = 0;
        for(int i =0 ; i<input.length(); i++){
            if(input.charAt(i) == 'a'){
                charCount++;
            }
        }
        System.out.println("count of character 'a' on String: 'Today is Monday' using for loop  " + charCount);
     
        //a more elegant way of counting occurrence of character in String using foreach loop
     
        charCount = 0; //resetting character count
        for(char ch: input.toCharArray()){
            if(ch == 'a'){
                charCount++;
            }
        }    
        System.out.println("count of character 'a' on String: 'Today is Monday' using for each loop  " + charCount);
    }
 
       
}

Output
count of occurrence of character 'a' on String: 'Today is Monday' using Spring StringUtils 2
count of character 'a' on String: 'Today is Monday' using commons StringUtils 2
count of character 'a' on String: 'Today is Monday' using for loop  2
count of character 'a' on String: 'Today is Monday' using for each loop  2


Well, the beauty of this questions is that Interviewer can twist it on many ways, they can ask you to write a recursive function to count occurrences of a particular character or they can even ask to count how many times each character has appeared.

So if a String contains multiple characters and you need to store count of each character, consider using HashMap for storing character as key and number of occurrence as value. Though there are other ways of doing it as well but I like the HashMap way of counting character for simplicity.

Other programming exercises for Java programmer


11 comments :

Anonymous said...

Collections.frequency() method might be useful in this case.

tejya gore said...

public class test
{
public static void main(String[] args)
{
String str = "ababccbdde";
int i,j,k;
char[] ch = str.toCharArray();
int len=ch.length;
for ( i = 0; i < len; i++) {
int counter = 0;
char c=str.charAt(i);
for ( j = 0; j < len; j++) {
if (c==ch[j]){
counter++;
ch[j]='\u0000';
}
}
if(counter>0)System.out.println(c+"="+counter);

}
}
}

nousheen ahmad said...

package selfpractice.array;

public class DistinctArray2 {

static String str = "sgsgsgsgs";
static String distinct = "";
static char[] charary = str.toCharArray();
static StringBuilder hello = new StringBuilder("");
static char[] tempcharary = new char[charary.length];
static int i;
static int count;
public static char[] getDistinctLetter()
{
int incr = 0;

for ( i = 0; i < charary.length; i++)
{
if (!(DistinctArray2.isletteroccure(charary[i])))
{

tempcharary[incr] = charary[i];
hello.append( tempcharary[incr]);
++incr;


}
}

char[] distinctresult = hello.toString().toCharArray();

for (int j = 0; j < distinctresult.length; j++)
{
for (int k = 0; k < charary.length; k++)
{
if (distinctresult[j] == charary[k])
{
++count;
}

}

System.out.println("LETTER " + tempcharary[j] + " OCCURE " + count + " TIMES ");
count = 0;

}

return tempcharary;

}



public static Boolean isletteroccure(char ch)
{
for (int j = 0; j < charary.length; j++)
{
if (ch == tempcharary[j])
{
return true;
}
}

return false;
}
public static void main(String[] args) {

DistinctArray2.getDistinctLetter();


}
}

Anonymous said...

Program to accept the string from command line and display
1. No. of words in string
2. No. of characters in each word
3. No. of characters in string

public class Str
{
public static void main(String args[])
{
int ch=0;
System.out.println("String is = ");
for(int i=0;i<args.length;i++)
{
System.out.println(args[i]);
}
System.out.println("Number of words in the string = "+args.length);
for(int i=0;i<args.length;i++)
{
String s=args[i];
ch=s.length()+ch;
System.out.println("Number of characters in -"+args[i]+"- = "+s.length());
}
System.out.println("No. of characters in string = "+ch);
System.out.println("No. of characters in string with white spaces ="+(ch+(args.length-1)));
}
}

Ramkumar Selvaraj said...

package String;
import java.util.Scanner;
public class Reverse {
@SuppressWarnings("resource")
public static void main(String[] args) {
int charCount = 0;
System.out.println("Enter the string:");

Scanner in = new Scanner(System.in);
String str = in.nextLine();
for(char ch = 'a' ; ch <= 'z' ; ch++ )
{
for(int i =0 ; i<str.length()-1; i++)
{
if(str.charAt(i) == ch)
{
charCount++;
}
}
if(charCount!=0){
System.out.println(ch+"="+charCount);
charCount=0;
}
}
}
}

Janardhan Randhi said...

public class Binary_Octal {

Scanner scan;
int num;

void getVal() {

System.out.println("Binary to Octal");
scan = new Scanner(System.in);

System.out.println("\nEnter the number :");
num = Integer.parseInt(scan.nextLine(), 2);
}

void convert() {

String octal = Integer.toOctalString(num);

System.out.println("Octal Value is : " + octal);
}
}

class MainClass {

public static void main(String args[]) {

Binary_Octal obj = new Binary_Octal();

obj.getVal();
obj.convert();
}
}


Sample Output

Binary to Octal

Enter the number :
1010
Octal Value is : 12

Vandana Mishra said...

import java.util.Scanner;

public class count {
public static void main(String[] args) {

Scanner scn = new Scanner(System.in);
System.out.println("Enter String");
String str = scn.nextLine();
System.out.println("Enter charcter to know its occurrence");
char c = scn.next().charAt(0);
int count =0;
for(int i=0;i<str.length();i++){
char ch = str.charAt(i);
if(ch==c){
count++;
}
}
System.out.println("count is:"+count);
}
}

Javin Paul said...

Hello Vandana, time complexity of your solution is O(n) as it need to iterate through array, can you better it?

Laki said...

Scanner s = new Scanner(System.in);
System.out.println("Enter some sentence");
String sentence = s.nextLine();
System.out.println("Enter word to to follow ");
char word = s.next().charAt(0);
int counter =0;
char[] chars = sentence.toCharArray();

for (int i = 0; i < chars.length; i++) {
System.out.print("| " + i + " |");
System.out.println(" " + chars[i] + " |");
System.out.println("-------------");
}

for (int i = 0; i < chars.length; i++) {

if(sentence.charAt(i) == word){
counter++;
}
}
System.out.println("Word " + word + " appears in sentence " + counter + " times");


s.close();

srikanth patil said...

count the no of characters in a string

srikanth patil said...

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s= " hello srikanth";
int count=0;;
for(int i=0;i<s.length();i++)
{boolean b=Character.isWhitespace(s.charAt(i));


if(b==false)
{
count++;
}
}

System.out.println(count);
}
}

id this fine or not

Post a Comment