检测.txt文档出现某字符串的次数。
首先简单写了一个测试文档,可以直观的看到出现了6次“我”,2次“是我”,3次“小饼干”。
测试结果正确。
这里以小说《南渡北归》为例,检测出现“我”、“梅贻琦”两个字符串出现的次数。
代码如下:
import java.io.*;
import java.util.Scanner;
class StrCompare
{
public static void main(String[] args) throws IOException,NullPointerException
{
BufferedReader reader=new BufferedReader(new FileReader(new File("E:/java task/cookie reader/南渡北归(三部曲).txt")));
String s = reader.readLine(); //读取行数
System.out.println("请输入关键字:");
Scanner sc=new Scanner(System.in);//从键盘接收数据
String str=sc.nextLine();
char[] ch=str.toCharArray();
int count=0;
while (s != null) //确定行数不为空
{
boolean b=s.contains(str);//子字符串是否被包含在此字符串之中,包含输出true,否则输出false
String[] st=new String[s.length()-ch.length+1];
if(b==true)
{
for(int i=0;i<st.length;i++)
{
st[i]= s.substring(i,i+ch.length);
if(st[i].equals(str))
{
count++;
}
}
}
s = reader.readLine();
}
System.out.println("包含 "+str+" 次数为:"+count);//调用count,输出包含次数
}
}
结果如下: