如何统计txt文件中某个字符出现的次数java正则表达式



如何统计txt文件中某个字符出现的次数?那么使用什么方法比较便捷快呢?大家在遇到这个题的时候,可能都回在想算法的问题,忽视了正则表达式,事实上我们使用正则表达式就可以很好地处理类似的问题。

java正则表达式代码很简单,就是很多人没有想到用正则,下面来模拟一下:

import java.io.*;
import java.util.regex.*;
class text{
public static void main(String args[])throws Exception{

BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(“wode.txt”)));
String s=”";
Pattern p=Pattern.compile(“\\bthis\\b”);//统计 this 出现的次数
//Pattern p=Pattern.compile(“\\ba\\b”);//统计 a 出现的次数
int count=0;
while((s=br.readLine())!=null){
Matcher m=p.matcher(s);
while(m.find()){
count++;
System.out.print(“start:”+m.start());
System.out.println(“end:”+m.end());
}

}
System.out.println(count);
}
}

下面是哪个wode.txt文件内容:this this this this this  a a a athis this