您的位置:首页 > 其它

找出字符串中所有重复的字符及其重复次数

2014-04-24 16:07 239 查看
思路:假设要统计的字符串是ASCII表示的,首先使用一个辅助数组用于统计每一个字符的重复次数,将其记录在下标为ASCII值的数组中,然后输出重复次数大于1的那些字符。

public static void statisticalLetterNumber(char[] ch) {
if (null == ch) {
return;
}

int count[] = new int[128];
Arrays.fill(count, 0);

for (int i = 0; i < ch.length; ++i) {
++count[(int) ch[i]];
}

for (int i = 0; i < 128; ++i) {
if (count[i] > 1) {
System.out.println((char) i + "=" + count[i]);
}
}
}

测试代码

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = null;
while ((string = scanner.next()) != null) {
statisticalLetterNumber(string.toCharArray());
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string ascii
相关文章推荐