(1)利用键盘录入,输入一个字符串
public static void main(String[] args) {
String str = inputString();
Map<Character, Integer> map = new HashMap<>();
map = countLetter(str,map);
printMap(map);
}
private static String inputString() {
System.out.println("请输入一句话:");
String str = new Scanner(System.in).nextLine();
return str;
}
(2)统计该字符串中各个字符的数量
private static Map<Character, Integer> countLetter(String str, Map<Character, Integer> map) {
char[] array = str.toCharArray();
Set<Character> set = map.keySet();
for(char c : array){
if(set.contains(c)){
map.put(c, map.get(c)+1);
}else{
map.put(c, 1);
}
}
return map;
}
(3)如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序输出结果:-(9)I(2)_(3)a(7)c(2)d(1)e(6)f(2)g(1)h(4)i(1)j(1)k(2)l(1)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
private static void printMap(Map<Character, Integer> map) {
String str="";
Set<Character> set = map.keySet();
for(char c : set){
str = str + c +"("+map.get(c)+")";
}
System.out.println(str);
}