统计文件每个字母出现次数

论坛 期权论坛 脚本     
匿名技术用户   2021-1-2 22:20   125   0
统计本项目中(所有java文件中)每个字母出现的次数(不用按照字母的顺序排列),按照如下格式打印:

a(1000)b(2000)c(3000)d(4000)


大致如下:

public class A {

 public static void main(String[] args) throws IOException {
  
  StringBuilder sb = new StringBuilder();
  
  File directory = new File("");//参数为空 
  String courseFile = directory.getCanonicalPath()+"/file.java"; 
  
  BufferedReader bf = new BufferedReader(new FileReader(courseFile));
  
  String content = null;
  
  while((content = bf.readLine()) != null){
   sb.append(content.trim());
  }
  //如果只统计小写,就传递'a', 'z'进去  
  countCracts(sb.toString(), 'a', 'z');
  System.out.println();
  //大写,'A'-'Z'
  countCracts(sb.toString(), 'A', 'Z');
 }
 private static void countCracts(String str, char start, char end) {
  for(char a = start; a <= end; a++){
   int cractCount = str.length() - str.replaceAll(String.valueOf(a), "").length();
   System.out.print(a + "(" + cractCount+")");
  }
 }
    
}


分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP