package com.itheima;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;
/* 7、 取出一个字符串中字母出现的次数。如:字符串:"abcdekka27qoq" ,输出格式为:a(2)b(1)k(2)...
*/
public class ExamTest7 {
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 + ")");// 按规定的格式输出
}
}
} |
|