168、有一个字符串,其中包含中文字符、英文字符和数字字符,请统计和打印出各个字符的个数。
答:哈哈,其实包含中文字符、英文字符、数字字符原来是出题者放的烟雾弹。
String content = “中国aadf的111萨bbb菲的zz萨菲”;
HashMap map = new HashMap();
for(int i=0;i<content.length;i++)
{
char c = content.charAt(i);
Integer num = map.get(c);
if(num == null)
num = 1;
else
num = num + 1;
map.put(c,num);
}
for(Map.EntrySet entry : map)
{
system.out.println(entry.getkey() + “:” + entry.getValue());
}
估计是当初面试的那个学员表述不清楚,问题很可能是:
如果一串字符如"aaaabbc中国1512"要分别统计英文字符的数量,中文字符的数量,和数字字符的数量,假设字符中没有中文字符、英文字符、数字字符之外的其他特殊字符。
int engishCount;
int chineseCount;
int digitCount;
for(int i=0;i<str.length;i++)
{
char ch = str.charAt(i);
if(ch>=’0’&& ch<=’9’)
{
digitCount++
}
else if((ch>=’a’ && ch<=’z’) || (ch>=’A’ && ch<=’Z’))
{
engishCount++;
}
else
{
chineseCount++;
}
}
System.out.println(……………);
欢迎光临 飞网论坛 (https://bbs.cfei.net/) | Powered by Discuz! X3.2 |