【问题标题】:count specific characters in a string (Java)计算字符串中的特定字符(Java)
【发布时间】:2012-06-07 16:18:49
【问题描述】:

我有一个家庭作业来计算字符串中的特定字符。

例如:string = "America"

输出应该是 = a appear 2 times, m appear 1 time, e appear 1 time, r appear 1 time, i appear 1 time and c appear 1 time

public class switchbobo {

/**
 * @param args
 */     // TODO Auto-generated method stub
  public static void main(String[] args){
    String s = "BUNANA";
    String lower = s.toLowerCase();
    char[] c = lower.toCharArray(); // converting to a char array
    int freq =0, freq2 = 0,freq3 = 0,freq4=0,freq5 = 0;

    for(int i = 0; i< c.length;i++) {
        if(c[i]=='a') // looking for 'a' only
          freq++;
        if(c[i]=='b')
          freq2++;
        if (c[i]=='c') {
          freq3++;
        }

        if (c[i]=='d') {
          freq4++;
        }       
    }
    System.out.println("Total chars "+c.length);
    if (freq > 0) {
      System.out.println("Number of 'a' are "+freq);
    }
  }
}

上面的代码是我所做的,但我认为拥有 26 个变量(每个字母一个)是没有意义的。你们有其他结果吗?

【问题讨论】:

  • 使用具有 26 个索引的数组。 ('a'-'a' == 0, 'b' - 'a' == 1,依此类推)。

标签: java string char histogram


【解决方案1】:

显然,您对每个字母都有一个变量的直觉是正确的。

问题是你没有任何自动化的方法来对不同的变量做同样的工作,你没有任何简单的语法可以帮助你对 26 个不同的变量做同样的工作(计算单个字符的频率) .

那你能做什么?我会提示您两种解决方案:

  • 您可以使用数组(但您必须找到将字符 a-z 映射到索引 0-25 的方法,这在某种程度上是微不足道的,因为您需要 ASCII 编码)
  • 您可以使用HashMap&lt;Character, Integer&gt;,它是一个关联容器,在这种情况下,您可以将数字映射到特定字符,从而完全满足您的需求

【讨论】:

【解决方案2】:

您可以使用HashMap的字符键和整数值。

HashMap<Character,Integer> 

遍历字符串

-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

这是一个伪代码,你必须尝试编码它

【讨论】:

    【解决方案3】:

    继续 Jack 的回答,以下代码可能是您的解决方案。它使用一个数组来存储字符的频率。

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

    它将给出以下输出:

    Total chars 6
    a       2
    b       1
    n       2
    u       1
    

    【讨论】:

    • 关于代码 c[i]-97,它会按预期工作吗?这对我来说是个嫌疑犯,因为变量 c 是 char 类型,它减去一个整数。在 C 语言中,您可以使其工作,但 Java 是一种更严格的类型语言。因此我不鼓励它。使用 ASCII 编码更安全、更传统。例如,字母“a”的 ASCII 值是多少?
    • @TheOriginalAndroid:是的。如果没有,我就不会发布它。 When an arithmetic operation is performed between a character and an integer, it is actually performed between the ascii value of the character and the integer. The result of such operation is also an integer.'a'的ascii值为97!!
    【解决方案4】:

    我正在使用 HashMap 作为解决方案。

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

    产生的输出 - {U=2, A=3, B=2, N=3}

    【讨论】:

    • 你试过了吗?因为它给每个字母+1
    【解决方案5】:
    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']++
    

    【讨论】:

      【解决方案6】:
      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);
      
              }
          }
      }
      

      【讨论】:

      • 欢迎使用 stackoverflow,如果您提供一些解释以配合您的代码,它会有所帮助。通过这种方式,而不是复制/粘贴并希望它有效,提出问题的人将能够看到为什么某些东西有效,以及为什么没有
      【解决方案7】:

      也许你可以用这个

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

      例如:

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

      【讨论】:

        【解决方案8】:

        在字符串中计数 char 'l'。

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

        int count=  StringUtils.countMatches("Hello", "l");
        

        【讨论】:

          猜你喜欢
          • 2014-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多