Java统计字符串中每个字符出现次数package com.perry.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
*
* @author perry_zhao
* 统计一个字符串中每个字符出现的次数(不忽略大小写)
*/
public class CountStr {
public Map count(String str){
System.out.println("需要统计的字符串:"+str+"准备开始统计每个字符出现的次数...");
Map<String,Integer> map = new HashMap<String,Integer>();
String temp ="";
for(int i=0; i<str.length(); i++){
temp = str.substring(i, i+1);
if(map.size()==0){
//map集合中没数据,将第一个数据加进去
map.put(temp, 1);
}else{
if(map.get(temp)==null){
//map集合中没有,将其加入
map.put(temp, 1);
}else{
//map集合中存在,将其value值加1
int n = map.get(temp);
n+=1;
map.put(temp, n);
}
}
}
return map;
}
public static void main(String[] args) {
Count count = new Count();
Map map = count.countStr("this is test data");
//以下是对Map集合中的数据进行跌倒传统的方法
Set set = map.keySet();
Iterator it = set.iterator();
while(it.hasNext()){
String key = (String)it.next();
int number = (Integer)map.get(key);
System.out.print(key+":"+number+"次;");
}
}
}。