统计字符串中每个字母的个数
思路:
从文件中读取字符串的内容,以字母为键(key),出现次数为值(value)存入HashMap集合中,在读入时判断集合是否存在当前字符的key,不存在则作为键值对存入集合,若存在说明出现过,value值+1,键值对覆盖存入集合中。
public class WorkDemo1 {
public static void main(String[] args) {
try {
Map<Integer,Integer> result=new TreeMap<>();
//创建FileReader对象
FileReader fr=new FileReader("D:/test2/4.txt");
//每次读取一个字符
int code=0;
while((code=fr.read())!=-1) {
//判断的map集合是否存在某个key
if(result.containsKey(code)) {
result.put(code, result.get(code)+1);
}else {
result.put(code,1);
}
}
//遍历result集合,打印结果
Set<Entry<Integer, Integer>> entrySet = result.entrySet();
for(Entry<Integer,Integer> e:entrySet) {
int c=e.getKey();
System.out.print((char)c+"("+e.getValue()+")"+"\t");
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
该博客介绍了一种统计字符串中每个字母出现次数的方法,通过读取字符串内容并利用HashMap存储字母作为键,出现次数作为值。在遍历过程中,如果HashMap中不存在当前字母,则添加键值对;如果存在,则更新值并覆盖存入。
1100

被折叠的 条评论
为什么被折叠?



