分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"Ifyou-wanttochange-your_fate_I_thinkyoumustcome-to-the-dark-horse-to-learn-java"
程序输出结果: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)-(9)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
代码实现:
import java.util.HashMap;
/*分析以下需求,并用代码实现:
(1)利用键盘录入,输入一个字符串
(2)统计该字符串中各个字符的数量
(3)如:
用户输入字符串"If~you-want~to~change-your_fate_I_think~you~must~come-to-the-dark-horse-to-learn-java"
程序输出结果: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)-(9)m(2)n(4)o(8)r(4)s(2)t(8)u(4)v(1)w(1)y(3)~(6)
*/
import java.util.Scanner;
public class CountString {
public static void main(String[] args) {
String s = new Scanner(System.in).next();
String[] str = s.split("");
HashMap<String,Integer> hm = new HashMap<>();
for(int i=0 ; i<str.length ; i++) {
if(!hm.containsKey(str[i]))
hm.put(str[i], 1);
else {
int value = hm.get(str[i]);
value++;
hm.put(str[i], value);
}
}
for(String key : hm.keySet())
System.out.print(key+"("+hm.get(key)+")");
}
}
输出结果: