count specific characters in a string (Java)

ぐ巨炮叔叔 提交于 2019-12-01 17:10:14

Obviously your intuition of having a variable for each letter is correct.

The problem is that you don't have any automated way to do the same work on different variables, you don't have any trivial syntax which helps you doing the same work (counting a single char frequency) for 26 different variables.

So what could you do? I'll hint you toward two solutions:

  • you can use an array (but you will have to find a way to map character a-z to indices 0-25, which is somehow trivial is you reason about ASCII encoding)
  • you can use a HashMap<Character, Integer> which is an associative container that, in this situation, allows you to have numbers mapped to specific characters so it perfectly fits your needs

You can use HashMap of Character key and Integer value.

HashMap<Character,Integer> 

iterate through the string

-if the character exists in the map get the Integer value and increment it.
-if not then insert it to map and set the integer value for 0

This is a pseudo code and you have to try coding it

I am using a HashMap for the solution.

import java.util.*;

public class Sample2 {

/**
 * @param args
 */
public static void main(String[] args) 
 {
    HashMap<Character, Integer> map = new HashMap<Character, Integer>();
    String test = "BUNANA";
    char[] chars = test.toCharArray();

    for(int i=0; i<chars.length;i++)
    {
        if(!map.containsKey(chars[i]))
        {
            map.put(chars[i], 1);
        }
        map.put(chars[i], map.get(chars[i])+1);
    }

    System.out.println(map.toString());
 }

}

Produced Output - {U=2, A=3, B=2, N=3}

In continuation to Jack's answer the following code could be your solution. It uses the an array to store the frequency of characters.

public class SwitchBobo 
{
   public static void main(String[] args)
   {
      String s = "BUNANA";
      String lower = s.toLowerCase();
      char[] c = lower.toCharArray();
      int[] freq = new int[26];
      for(int i = 0; i< c.length;i++) 
      {
         if(c[i] <= 122)
         {
            if(c[i] >= 97)
            {
               freq[(c[i]-97)]++;
            }
         }        
      }
      System.out.println("Total chars " + c.length);
      for(int i = 0; i < 26; i++)
      {
         if(freq[i] != 0)   
            System.out.println(((char)(i+97)) + "\t" + freq[i]);
      }      
   }
}

It will give the following output:

Total chars 6
a       2
b       1
n       2
u       1
int a[]=new int[26];//default with count as 0
for each chars at string
if (String having uppercase)
  a[chars-'A' ]++
if lowercase 
then a[chars-'a']++
public class TestCharCount {
    public static void main(String args[]) {
        String s = "america";
        int len = s.length();
        char[] c = s.toCharArray();
        int ct = 0;
        for (int i = 0; i < len; i++) {
            ct = 1;
            for (int j = i + 1; j < len; j++) {
                if (c[i] == ' ')
                    break;
                if (c[i] == c[j]) {
                    ct++;
                    c[j] = ' ';
                }

            }
            if (c[i] != ' ')
                System.out.println("number of occurance(s) of " + c[i] + ":"
                        + ct);

        }
    }
}

maybe you can use this

public static int CountInstanceOfChar(String text, char character   ) {
    char[] listOfChars = text.toCharArray();
    int total = 0 ;
    for(int charIndex = 0 ; charIndex < listOfChars.length ; charIndex++)
        if(listOfChars[charIndex] == character)
            total++;
    return total;
}

for example:

String text = "america";
char charToFind = 'a';
System.out.println(charToFind +" appear " + CountInstanceOfChar(text,charToFind) +" times");

Count char 'l' in the string.

  String test = "Hello";
  int count=0;
  for(int i=0;i<test.length();i++){
   if(test.charAt(i)== 'l'){
       count++;
        }
    }

or

int count=  StringUtils.countMatches("Hello", "l");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!