• Register
0 votes
143 views

Problem :

How to count the number of occurrences of a character in a string in java
6 5 3
6,930 points

Please log in or register to answer this question.

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;
}

9 7 4
38,600 points
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); 
   } 
}

 

10 6 4
31,120 points

Related questions

0 votes
1 answer 5 views
5 views
Problem: I&rsquo;m new in java. How do I count the number of occurrences of a char in a String? I have the string a.b.c.d I want to count the occurrences of '.' in an idiomatic way, preferably a one-liner. How to count it? Please help me to learn. Thanks.
asked Mar 15 Sabbir Hossain 14.6k points
1 vote
1 answer 31 views
31 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, 2020 Gavin 15.3k points
1 vote
1 answer 6 views
6 views
Problem; Need help with the count of substring in Java. Count the number of occurrences of substring in a string in java.
asked Mar 29 PkGuy 23.5k points
1 vote
1 answer 9 views
9 views
Problem: I am having an issue ,will some body help me here? Find number of occurrences of a character in a string python.
asked May 1 PkGuy 23.5k points
0 votes
1 answer 6 views
6 views
Problem: Is there any way to count number of occurrences of character in string java ?
asked Apr 9 zayed1 61.8k points
0 votes
1 answer 44 views
44 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, 2020 LizzyM 6.1k points
1 vote
1 answer 24 views
24 views
Problem: I tried to count occurrences of individual character of string using python. So I wrote this program for the string: a = 'yanwawny' The program: ​​​string = 'yanwawny' ​dict((letter, string.count(letter)) for letter in set(a) But it throws the error message: File "main.py", line 1 ​a = 'yanwawny' ^ SyntaxError: invalid character in identifier What to do to solve this thing?
asked May 4, 2020 samhaz 5k points
0 votes
1 answer 11 views
11 views
Problem: we are going to figure out how many times a word is repeated in the text file using a map interface method through a Java program. I don&rsquo;t know how to count the number of occurrences of a word in a text file using a hash-map then you are at the right place to know your problem&rsquo;s solution?
asked Dec 2, 2020 Mashhoodch 13k points
0 votes
1 answer 15 views
15 views
Problem: Please help me to count number of occurrences in string in Javascript
asked Mar 20 Ifra 37.2k points
0 votes
1 answer 5 views
5 views
Problem: I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this: String s = "House, House, House, Dog, Dog, Dog, Dog"; I need to create a new string list without repetitions and ... ? I've managed to separate the string using s.split() but then how do I count repetitions and eliminate them on the new string? Thanks!
asked Apr 24 Humaira ahmed 50.7k points