思路:
每次读取一个字符
判断map集合中是否存在当前字符的key
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
}
}
通过读取文件内容,逐字符分析,利用Map数据结构存储每个字符及其出现次数,实现对文件中字符串中字母个数的统计。

1万+

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



