a- /**
- * 需求:统计输入的字符串,如 "abcaab" 以a(3)b(2)c(1)的形式输出
- * 分析: 1 字符与字符个数属于对应关系,可用Map<String,Integer>
- * 2 输出字母是自然排序,所以考虑使用TreeMap
- */
- package fmi1;
- import java.util.Scanner;
- import java.util.Set;
- import java.util.TreeMap;
- public class CharacterCount {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- //建立接收键盘输入的字符串
- System.out.println("请输入字符串:");
- String line = new Scanner(System.in).nextLine();
- //建立集合Map
- TreeMap<Character, Integer> tm = new TreeMap<Character,Integer>();
- //将输入字符串转成数组
- char[] chs = line.toCharArray();
- //遍历字符串,将字符存入集合Map,若字符key已存在,则value加1,否则,value = 1
- for(char ch:chs ){
- //根据键获取集合的值,判断字符的个数
- Integer value = tm.get(ch);
- if(null == value){//没有对应键值对
- value = 1;
- }
- else
- value++;
- //将更新后的键值关系存至Map
- tm.put(ch, value);
- }
- //遍历Map,输出键值对
- StringBuilder sb = new StringBuilder("");
- Set<Character> s = tm.keySet();
- for(Character ch:s){
- sb.append(ch).append("(").append(tm.get(ch)).append(")");
- }
- System.out.println(sb.toString());
- }
- }
复制代码
|
|