版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37036984/article/details/79472717
题目:java实现计算出字符串中每个字母出现次数
示例:
输入字符串为:aBcdenffdhanbcdeefe+- ..
输出字符串为:B(1)a(2)b(1)c(2)d(3)e(4)f(3)h(1)n(2)
括号内数字为前面字母出现次数
实现代码:
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
public class CountCharacter {
public static void main(String[] args) {
String str = "aBcdenffdhanbcdeefe+- ..";
System.out.println("输入字符串为:"+str);
String count = countCharacter(str);
System.out.println("输出字符串为:"+count);
System.out.println("括号为前面字母出现次数");
}
public static String countCharacter(String str) {
char[] c = str.toCharArray();
Map<Character,Integer> map = new TreeMap<Character,Integer>();
for(int i = 0;i<c.length;i++){
Integer value = map.get(c[i]);
if(!(c[i]>='a'&&c[i]<='z'||c[i]>='A'&&c[i]<='Z'))
continue;
if(value==null)
map.put(c[i], 1);
else
map.put(c[i], value+1);
}
return maptoString(map);
}
private static String maptoString(Map<Character, Integer> map) {
StringBuilder str = new StringBuilder();
Iterator<Character> it = map.keySet().iterator();
while(it.hasNext()){
Character key = it.next();
Integer value = map.get(key);
str.append(key+"("+value+")");
}
return str.toString();
}
}
输出结果:
输入字符串为:aBcdenffdhanbcdeefe+- ..
输出字符串为:B(1)a(2)b(1)c(2)d(3)e(4)f(3)h(1)n(2)
括号为前面字母出现次数