java检测.txt文档出现某个字符串的次数

检测.txt文档出现某个字符串的次数。

首先简单写了一个测试文档,可以清楚的看出有3个“这”,2个“我”。
在这里插入图片描述
测试结果正确。
在这里插入图片描述

这里以小说《南渡北归》为例,检测出现“我”、“梅贻琦”两个字符串出现的次数。

代码如下:

import java.io.*;
import java.util.Scanner;
class  StrCompare
{
	public static void main(String[] args) throws IOException,NullPointerException
	{
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("E:/java task/cookie reader/南渡北归(三部曲).txt"))); //使用缓冲区的方法将数据读入到缓冲区中
        LineNumberReader reader = new LineNumberReader(br); 
		String s = reader.readLine(); //读取行数
		System.out.println("请输入关键字:");
		Scanner sc=new Scanner(System.in);//从键盘接收数据
		String str=sc.nextLine();
		int count=0;
        while (s != null) //确定行数不为空
		{            
			boolean b=s.contains(str);//子字符串是否被包含在此字符串之中,包含输出true,否则输出false
			//System.out.println("子字符串是否被包含在此字符串之中:"+b);
			if(b==true)
			{
			count++;
			}
			s = reader.readLine(); 
        } 
		System.out.println("包含  "+str+"   次数为:"+count);//调用count,输出包含次数
        reader.close(); 
        br.close(); 
	}
}

结果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42014622/article/details/83996504