还是写一下代码吧,这个题不难,但是很重要
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str = sc.nextLine();
char[] ch = str.toCharArray();// 转换成字符数组
TreeMap<Character, Integer> map = new TreeMap<>();// 创建一个TreeMap
for (char c : ch) {// 遍历
Character key = c;
Integer value = map.get(c);
if (value == null) {// 判断,如果值为空,则向集合中添加(key,1),如果不为空则添加 (key,value+1)
map.put(key, 1);
} else {
map.put(key, value + 1);
}
}
// 遍历集合
Set<Map.Entry<Character, Integer>> set = map.entrySet();
Iterator<Entry<Character, Integer>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<Character, Integer> me = it.next();
Character key = me.getKey();
Integer value = me.getValue();
System.out.println(key + "(" + value + ")");// 按规定的格式输出
}
}
}
还有一种Stringbuffer的append()方法,你自己做吧 |