【发布时间】: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