import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Map.Entry; import java.util.Scanner; import java.util.Set; /*分析以下需求,并用代码实现 1.利用键盘录入,输入一个字符串 2.统计该字符串中各个字符的数量(提示:字符不用排序) 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)*/ public class t6 { public static void main(String[] args) { //创建键盘录入对象 Scanner sc = new Scanner(System.in); System.out.println("请输入一个字符串:"); //接收字符串 String s = sc.nextLine(); //将字符串转换成数组 char[] ch = s.toCharArray(); //创建Map集合 HashMap<Character, Integer> hm = new HashMap<Character, Integer>(); //遍历字符数组 for (int i = 0; i < ch.length; i++) { //将数组中的字符作为键去查询map表 Integer value = hm.get(ch[i]); //判断值是否为null int count = 0; if( value != null) { count = value; } count++; hm.put(ch[i], count); } //遍历集合 Set<Entry<Character, Integer>> entrys = hm.entrySet(); for (Entry<Character, Integer> entry : entrys) { Character key = entry.getKey(); Integer value = entry.getValue(); System.out.print(key+"("+value+")"); } } }
统计字符串中各个字符的数量(提示:字符不用排序)
猜你喜欢
转载自blog.csdn.net/ludadan/article/details/79947038
今日推荐
周排行