• Register
search
Log In
0 votes
97 views

Problem :

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

2 Answers

0 votes

Solution :

Bellow is definitely the fastest way. Regexes are very slow here, and also harder to understand.
public int countChar(String str, char c)
{
    int count = 0;

    for(int i=0; i < str.length(); i++)
    {    if(str.charAt(i) == c)
            count++;
    }

    return count;
}

36.1k points
edited by
0 votes

Solution:

Follow the below program

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


Read more: https://javarevisited.blogspot.com/2012/12/how-to-count-occurrence-of-character-in-String.html#ixzz6NR7fI6R7

or follow the below steps

class NoOfOccurenceOfCharacters { 
	static final int MAX_CHAR = 256; 

	static void getOccuringChar(String str) 
	{ 
		// Create an array of size 256 i.e. ASCII_SIZE 
		int count[] = new int[MAX_CHAR]; 

		int len = str.length(); 

		// Initialize count array index 
		for (int i = 0; i < len; i++) 
			count[str.charAt(i)]++; 

		// Create an array of given String size 
		char ch[] = new char[str.length()]; 
		for (int i = 0; i < len; i++) { 
			ch[i] = str.charAt(i); 
			int find = 0; 
			for (int j = 0; j <= i; j++) { 

				// If any matches found 
				if (str.charAt(i) == ch[j]) 
					find++;				 
			} 

			if (find == 1) 
				System.out.println("Number of Occurrence of " + 
				str.charAt(i) + " is:" + count[str.charAt(i)]);			 
		} 
	} 
	public static void main(String[] args) 
	{ 
		Scanner sc = new Scanner(System.in); 
		String str = "geeksforgeeks"; 
		getOccuringChar(str); 
	} 
} 

or try this way

class JavaExample {  

   static void countEachChar(String str) 
   { 
	//ASCII values ranges upto 256
	int counter[] = new int[256]; 

	//String length
	int len = str.length(); 

	/* This array holds the occurrence of each char, For example
	 * ASCII value of A is 65 so if A is found twice then 
	 * counter[65] would have the value 2, here 65 is the ASCII value
	 * of A
	 */
	for (int i = 0; i < len; i++) 
		counter[str.charAt(i)]++; 

	// We are creating another array with the size of String
	char array[] = new char[str.length()]; 
        for (int i = 0; i < len; i++) { 
	   array[i] = str.charAt(i); 
	   int flag = 0; 
	   for (int j = 0; j <= i; j++) { 

		/* If a char is found in String then set the flag 
		 * so that we can print the occurrence
		 */
		if (str.charAt(i) == array[j])  
			flag++;                 
	   } 

	   if (flag == 1)  
	      System.out.println("Occurrence of char " + str.charAt(i)
		 + " in the String is:" + counter[str.charAt(i)]);             
	} 
   } 
   public static void main(String[] args) 
   {  
	String str = "beginnersbook"; 
	countEachChar(str); 
   } 
}

 

12.8k points

Related questions

1 vote
1 answer 7 views
7 views
Problem: Hello All, I am a novice in Java programming. I am learning Java by taking an online class out of my own curiosity. I am solving basic level problems from many websites. So far, I was doing good. I get stuck as soon as I get a problem that asked ... characters in a string but how to solve this particular problem? Do you guys have any idea? Please, help me to solve the problem. Thanks.
asked Apr 14 Gavin 15k points
2 votes
1 answer 14 views
14 views
Problem: Hello guys, I hope you all are doing well. I am learning java programming in my school. My teacher taught us many things about the string in the last class and gave a problem to solve. I tried to solve the problem but couldn&rsquo;t make it happen so far. ... problem I&rsquo;d be grateful to him/her. So, my problem is: find all occurrences of a substring in a string java Thanks, mate.
asked Mar 25 Gavin 15k points
1 vote
1 answer 19 views
19 views
Problem : I am a Computer Science student. I am trying to learn Java Programming in this Covid19 lockdown period. I want to write a program which should perform the below task. “Write a java program to count number of characters in given string”. Please let me know the exact procedure to write the above mentioned program.
asked May 19 Martin K 6.6k points
0 votes
1 answer 18 views
18 views
How to get the number from the occurences of individual characters Supose the string is: x = 'cdfghcfonccn' How can i solve this problem.
asked Mar 10 LizzyM 5.7k points
0 votes
1 answer 13 views
13 views
Problem: Hello kodlogs, Recently while attempting, the problem in the python there is a error that came can you please help sort out this problem, How can I get the first character from the first string in Python?,It seems that I could use list[0][1:] but that does not give me the first character of the string that I am looking for. mysrt = "sdf" >>> mystr[0][1:]
asked Jun 6 Gavin 15k points