java用Map统计字符串中每个字符出现的次数

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

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,生活是一杯酒,生活是一首诗";
String count =getCount(str);
System.out.println(count);
}
// 获取统计的方法
public static String getCount(String str)
{
char [] ch = str.toCharArray();
Map<Character,Integer> map = new TreeMap<Character,Integer>();
for (int i = 0; i < ch.length; i++)
{
// 只统计里面英语字母的个数
// if(!(ch[i]>'a'&&ch[i]<'z'||ch[i]>'A'&&ch[i]<'Z'))
// continue;
// 只统计其中汉字个数
//
// if(!(ch[i]>='一'&&ch[i]<='龥'))
// \u4e00 \u9fa5
// continue;
// 获取字符数组顺序对应的值
Integer value = map.get(ch[i]);
int count=1;
if(value!=null)
{
count = value+1;
}
map.put(ch[i], count);
}
return toNewString(map);
}
//将麻婆 Map 结果转换成自定义格式的字符串
public static String toNewString(Map<Character,Integer> map) {
StringBuilder sb = new StringBuilder();
Iterator <Entry<Character,Integer>> it = map.entrySet().iterator();
while(it.hasNext())
{
Entry<Character, Integer> en = it.next();
char cha= en.getKey();
int value = en.getValue();
sb.append(cha+"{"+value+"}"+" ");
}
return sb.toString();
}
}
运行效果:
统计全部字符串出现次数
只统计其中每个汉字出现的次数
只统计其中每个英文字母出现的次数。

相关文档
最新文档