《java用Map统计字符串中每个字符出现的次数.doc》由会员分享,可在线阅读,更多相关《java用Map统计字符串中每个字符出现的次数.doc(3页珍藏版)》请在金锄头文库上搜索。
1、package com.baidu.oct4;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.TreeMap;/*用 Map统计字符串中每个字符出现的个数 * (可以加限制条件,只统计英语字母或者汉字等) * */public class TreeSetDemo public static void main(String args)String str = abcdefyadhisn,xiednefmecd casdxsdffg$%tjukdfds,生活是一杯
2、酒,生活是一首诗;String count =getCount(str); System.out.println(count);/获取统计的方法public static String getCount(String str)char ch = str.toCharArray();Map map = new TreeMap();for (int i = 0; i a&chiA&chi=一&chi=龥)/u4e00 u9fa5/continue;/获取字符数组顺序对应的值Integer value = map.get(chi);int count=1;if(value!=null)count =
3、 value+1;map.put(chi, count);return toNewString(map);/将 麻婆 Map 结果转换成自定义格式的字符串public static String toNewString(Map map)StringBuilder sb = new StringBuilder();Iterator Entry it = map.entrySet().iterator();while(it.hasNext()Entry en = it.next();char cha= en.getKey();int value = en.getValue();sb.append(cha+value+ );return sb.toString(); 运行效果:统计全部字符串出现次数只统计其中每个汉字出现的次数只统计其中每个英文字母出现的次数