计算字符串中的特定字符(Java) [英] count specific characters in a string (Java)

查看:121
本文介绍了计算字符串中的特定字符(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a homework assignment to count specific chars in string.

例如: string =America

输出应为= a出现2次,m出现1次,e出现1次,r出现1次,我出现1次时间和c出现1次

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个变量(每个字母一个)没有意义。

code above is what I have done, but I think it is not make sense to have 26 variables (one for each letter). Do you guys have alternative result?

推荐答案

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

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

问题是,你没有任何自动化的方法在不同的变量上做同样的工作,你没有任何微不足道的语法,可以帮助你做同样的工作(计数一个char频率)为26个不同的变量。

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:


  • 你可以使用数组(但你必须找到一种方法映射字符 az 到索引 0-25 ,这是为什么是ASCII编码的原因)

  • 您可以使用 HashMap< Character,Integer> ;
  • 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

这篇关于计算字符串中的特定字符(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆