Sunday, September 24, 2023

How to Count Occurrences of a Character in String - Java Programming 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 is a very popular topic in programming interviews and there are a lot of good programming exercises 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 a solid knowledge of String in Java or any other programming language. Though, this question is mostly used to test the candidate's coding ability i.e. whether he can convert logic to code or not.

In the 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 is 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 a few) ways to count the number of occurrences of a character in String on Java.

Also, basic knowledge of essential data structure and algorithms is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to improve their knowledge and algorithms skills.



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 the occurrence of a character in String. Apache commons StringUtils provide the 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 characters using the standard for loop and Java 5 enhanced for loop. This solution can be extended not just to finding the occurrence of character but also to 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 a number of occurrences of any character on String:

import org.springframework.util.StringUtils;
/**
 * Java program to count the number of occurrences 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 the occurrence of a character in String using the 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 the 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 question is that the Interviewer can twist it in 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 the count of each character, consider using HashMap for storing characters as keys and the number of occurrences as value. Though there are other ways of doing it as well I like the HashMap way of counting characters for simplicity.


Other programming exercises for Java programmer

45 comments:

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

    ReplyDelete
  2. 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);

    }
    }
    }

    ReplyDelete
    Replies
    1. Good way to solve this problem for all characters.

      Delete
    2. public class Main {
      public static void main(String[] args) {
      int c1=0,c2=0;
      String s="java";
      char c=s.charAt(0);
      for(int i=0;ic2){
      c=s.charAt(i);
      c2=c1; }}
      c1=0;
      }
      System.out.println(c);
      }
      }

      Delete
  3. 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();


    }
    }

    ReplyDelete
  4. 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)));
    }
    }

    ReplyDelete
  5. 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;
    }
    }
    }
    }

    ReplyDelete
  6. 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

    ReplyDelete
  7. 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);
    }
    }

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

    ReplyDelete
  9. 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();

    ReplyDelete
  10. count the no of characters in a string

    ReplyDelete
  11. 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

    ReplyDelete
  12. static int c = 0;

    public static void main(String[] args) {
    String s = "aabbcfasdgalsgmvxnxbcsasfweasdgkandjkakjgaasdg";
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    String sortedString = new String(chars);

    count(sortedString);
    }

    public static void count(String str) {
    char[] chars = str.toCharArray();
    Set set = new HashSet();
    for(int i = 0; i < chars.length; i ++) {
    set.add(chars[i]);
    }
    List list = new ArrayList();
    for (Character string : set) {
    list.add(string);
    int occ = StringUtils.countOccurrencesOf(str, string.toString());
    System.out.print(string.toString() + occ);
    }
    }

    ReplyDelete
  13. Hello @Matt, can you please share the regular expression to count occurrence of any character in string, that will help better ..

    ReplyDelete
  14. Hello All, I m a beginner in java . I need to write a program for below:
    Given a Sentence , i need to color a sentence using minimum no. of Consonants. Each word in sentence can be colored by a single consonant
    ex: Hello How are you?
    Minimum no. of consonant to color sentence : 2
    i.e using o,e ( o occurs in 3 words: Hello,How ,you & e in are )
    therefore answer is 2


    Please help

    ReplyDelete
  15. str.split(c).length() - 1

    ReplyDelete
  16. String s="helppp";
    int c=0;
    char o=0;

    for (int i = 0; i 0)
    {
    System.out.println("char is repeated "+o+" at "+c+" times");
    }
    else
    {
    System.out.println("no char is repeated");
    }


    ReplyDelete
  17. import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;

    public class OccurenceofChar {

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Occurence occur=new Occurence();
    occur.Occurence("Today is Monday", 'o');

    }

    }
    class Occurence{
    public static int Occurence(String word, char letter) {
    Map map=new HashMap<>();
    char c[]=word.toCharArray();
    for(Character ch:c) {
    if(map.containsKey(ch)) {
    map.put(ch,map.get(ch)+1);
    }
    else {
    map.put(ch, 1);
    }
    }
    Set> entryset=map.entrySet();
    int occurence=0;
    for(Map.Entry entry: entryset) {
    if(entry.getKey()==letter) {
    occurence=entry.getValue();
    }
    }
    System.out.println(occurence);

    return occurence;
    }
    }

    ReplyDelete
  18. Nice solution, what are the test cases you have thought? Can you explain the Big(O) for space and time?

    ReplyDelete
  19. Wow surprised no one solved this recursively. Here you go with binary search:

    public static void main(String[] args) {
    int x = stringCounter("abacaaadeaac");
    System.out.println(x);
    }


    public static int stringCounter(String string){

    if(string.length() < 2){
    if(string.contains("a")){
    return 1;
    }
    return 0;
    }

    return stringCounter(string.substring(0,string.length()/2)) + stringCounter(string.substring(string.length()/2));


    }
    }

    ReplyDelete
  20. Recursive solution is good idea but I guess you need one more parameter to count occurence of a given character, right now you are just counting "a"

    ReplyDelete
  21. import java.util.*;
    public class solution {
    public static void main(String args[])
    {
    Scanner s=new Scanner(System.in);
    String in=s.nextLine();
    char c[]=in.toCharArray();
    List b=new ArrayList();
    for(char addchar:c)
    {
    b.add(addchar);
    }
    int g=0;
    int j=0;
    for(int i=0;ig)
    {
    j=i;
    g=n;
    }
    }
    System.out.println(c[j]);
    }
    }

    ReplyDelete
  22. function run() {

    var value = "add something here with many characters";
    var array = value.split("");
    var occurrences = {};

    array.forEach(function(val) {

    if(occurrences[val] == null || occurrences[val] == undefined){
    occurrences[val] = 1;
    } else {
    occurrences[val] += 1;
    }
    });

    console.log(occurrences);
    }

    ReplyDelete
  23. public static void main(String[]args){
    String s="laxmikanta";
    int count=s.length()-s.replace("a","").length();
    System.out.println("No of occurrence of a is:"+count);

    ReplyDelete
  24. import java.util.Scanner;
    public class HelloWorld{

    public static void main(String []args){
    // System.out.println("Hello World");
    Scanner sc=new Scanner(System.in);
    String str=sc.nextLine();
    int l=str.length();
    int max=0,temp=0,k=0;

    for(int i=0;imax)
    {
    max=temp;
    k=i;
    }
    }

    System.out.println("Character "+str.charAt(k)+" with max count "+max);

    }
    }

    ReplyDelete
  25. Hello @Unknown, blogger at the < sign, I assume its i < max right?

    ReplyDelete
  26. import java.util.*;
    class MaximumOccurring{
    public static void main(String args[]){
    Scanner sc=new Scanner(System.in);
    String str=sc.nextLine();
    char ch[]=str.toCharArray();

    char temp;
    for(int i=0;ich[j]){
    temp=ch[i];
    ch[i]=ch[j];
    ch[j]=temp;
    }
    }
    }
    int count=1;
    int arr[]=new int[str.length()];
    int k=0;
    char result[]=new char[str.length()];
    for(int i=0;imax){
    max=arr[i];
    index=i;
    }
    }

    System.out.println(ch[index]);
    }
    }

    ReplyDelete
  27. Hello all, String val=banana , a has been occurred 3 times, can any one help an code , i am new to coding.

    ReplyDelete
  28. using Java 8

    Stream charStream = word.chars().mapToObj(obj -> (char) obj);
    System.out.println(charStream.filter(c -> c == character).count());

    ReplyDelete
  29. neat example Anshul, thx for sharing with us.

    ReplyDelete
  30. public static void MaxOccChar() {
    String s="myy nameeee is Sama".toLowerCase();

    Map ch= new TreeMap();
    for(int i =0;i> retS=ch.entrySet();
    int max=0; char c='a';
    for(Entry e:retS) {
    if(max<e.getValue()) {
    max=e.getValue();
    c=e.getKey();}
    }
    System.out.println("Character "+c+" occurs maximum times & the count is "+max);

    }

    ReplyDelete
  31. public class sample4
    {
    public void vc(String str)
    {
    int vowels=0,consonants=0;
    for(int i=0;i<str.length();i++)
    {
    if((97<=str.charAt(i) && str.charAt(i)<=122) || (65<=str.charAt(i) && str.charAt(i)<=90))
    {
    if('a'==str.charAt(i) || 'e'==str.charAt(i) || 'i'==str.charAt(i) || 'o'==str.charAt(i) || 'u'==str.charAt(i))
    {
    vowels++;
    }
    else
    {
    consonants++;
    }
    }
    }
    System.out.print("The total vowels are :"+vowels);
    System.out.println();
    System.out.print("The total consonants are :"+consonants);
    }

    public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    String asp=sc.next();
    sample4 as=new sample4();
    as.vc(asp);
    }

    }

    ReplyDelete
  32. HashMap countM=new HashMap();

    for(int i=0;i<str.length();i++) {
    //System.out.println("SubString"+String.valueOf(str.charAt(i)));
    if(countM.get(String.valueOf(str.charAt(i)))==null) {
    countM.put(String.valueOf(str.charAt(i)), 1);
    }else {
    //System.out.println(String.valueOf(str.charAt(i))+" : "+countM.get(String.valueOf(str.charAt(i))));
    countM.put(String.valueOf(str.charAt(i)), countM.get(String.valueOf(str.charAt(i)))+1);
    }
    }
    System.out.println(countM);

    ReplyDelete
  33. public class MaxiOccurChar {

    public static void main(String[] args) {
    int count;
    String s="Java";
    int a[]=new int[s.length()];
    int max=a[0];
    int pos=0;
    // for counting char occurence
    for (int i = 0; i < s.length(); i++) {
    count=0;
    for (int j = i; j < s.length(); j++) {
    if(s.charAt(i)==s.charAt(j))
    {
    count++;
    }
    }
    a[i]=count;
    System.out.println(a[i]+" Count of chararcter "+s.charAt(i));
    // maximum occured char

    if(a[i]>max){
    max=a[i];
    pos=i;
    }
    }
    System.out.println("Maximum occur: "+max+" times for char: "+s.charAt(pos));


    }

    }

    ReplyDelete
  34. public static void main(String[] args) {
    String str="nnnaaaavvvsss is navin ssss lllllll tttttt";int result=0;
    HashMap hm=new HashMap();
    for(int i=0;i<=str.length()-1;i++) {
    if(hm.get(str.charAt(i))==null) {
    hm.put(str.charAt(i), 1);
    }
    else {
    hm.put(str.charAt(i), hm.get(str.charAt(i))+1);
    if(result<hm.get(str.charAt(i)))
    result=hm.get(str.charAt(i));
    }
    }

    System.out.println(result);
    }

    ReplyDelete
  35. public class MaxOccuringChar {

    public static void main(String[] args) {
    String s="atrtrayiuytrsaaouhgaaouja";

    char[] arr=s.toCharArray();
    Map map=new HashMap<>();
    Integer count=0;
    for (char c : arr) {
    if(map.containsKey(c)) {
    count= map.get(c) + 1;
    map.put(c, count);
    }else {
    count=count+1;
    map.put(c, count);
    }
    }

    int max = map.values().stream().max((a,b)-> a>b?a:b).get();
    System.out.println(max);
    }
    }

    ReplyDelete
  36. public static void findMaxOccurance(String str)
    {
    int count=0;
    int max_occurance=0;
    Character max_occ_character= 0;
    Map char_map=new HashMap<>();
    for(int i=0;i<str.length();i++)
    {
    count=1;
    if(char_map.containsKey(str.charAt(i))) {
    count = char_map.get(str.charAt(i)) + 1;
    }
    char_map.put(str.charAt(i), count);
    }
    for(Character key: char_map.keySet())
    {
    if(max_occurance < char_map.get(key)) {
    max_occ_character=key;
    max_occurance = char_map.get(key);
    }
    }
    System.out.println("max Occurrence character is " + max_occ_character +" Frequency is "+ max_occurance);
    }

    ReplyDelete
  37. public static void findMaxOccurance(String str)
    {
    int count=0;
    int max_occurance=0;
    Character max_occ_character= 0;
    Map char_map=new HashMap<>();
    for(int i=0;i<str.length();i++)
    {
    count=1;
    if(char_map.containsKey(str.charAt(i))) {
    count = char_map.get(str.charAt(i)) + 1;
    }
    char_map.put(str.charAt(i), count);
    }
    for(Character key: char_map.keySet())
    {
    if(max_occurance < char_map.get(key)) {
    max_occ_character=key;
    max_occurance = char_map.get(key);
    }
    }
    System.out.println("max Occurrence character is " + max_occ_character +" Frequency is "+ max_occurance);
    }

    ReplyDelete
  38. String str = "ababac";
    char chr[] = str.toCharArray();
    char c =' ';
    char f=' ';
    int temp=0;
    for(int i=0;itemp)
    {
    temp =count1;
    f=chr[i];
    }
    }
    System.out.println("char is = "+f+" count is = "+temp);

    ReplyDelete
  39. public class Sample{

    public static void main(String args[]){
    String str="sare jhan se aacha";
    int temp=0;
    int Char=0;

    for(int i=0;i<str.length();i++){
    int count=0;
    char currchar=str.charAt(i);
    for(int j=0;j<str.length();j++)
    {
    if(str.charAt(j)==currchar && str.charAt(j)!=' '){
    count++;
    }
    }
    if(temp<count){
    temp=count;
    Char=i;
    }
    }
    char z=str.charAt(Char);
    System.out.println("Highest occurance character is = "+z + "\n" +"occurance count is = "+ temp);

    }
    }

    ReplyDelete
  40. class Occ
    {
    public static void main(String[] arg)
    {
    String s = "This is a kumar sharma";
    String[] a = s.split("a");
    System.out.println(a.length);
    }
    }

    ReplyDelete
  41. class Occ
    {
    public static void main(String[] arg)
    {
    String s = "This is a kumar sharma";
    String[] a = s.split("a");
    System.out.println(a.length);
    }
    }

    ReplyDelete