use*_*513 8 java string char histogram
我有一个家庭作业来计算字符串中的特定字符.
例如: 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码是我所做的,但我认为有26个变量(每个字母一个)是没有意义的.你们有其他结果吗?
显然,你对每个字母都有一个变量的直觉是正确的.
问题是你没有任何自动方式对不同的变量做同样的工作,你没有任何简单的语法可以帮助你为26个不同的变量做同样的工作(计算一个char频率).
那你能做什么?我会暗示你走向两个解决方案:
a-z到索引0-25,这在某种程度上是微不足道的,你是因为ASCII编码的原因)HashMap<Character, Integer>哪个是关联容器,在这种情况下,允许您将数字映射到特定字符,以便它完全符合您的需求| 归档时间: |
|
| 查看次数: |
18265 次 |
| 最近记录: |