首页 > 其他 > 详细

读取一个文件,给定一个字符串,判断这个字符串在文件中出现的次数

时间:2018-08-23 14:43:00      阅读:170      评论:0      收藏:0      [点我收藏+]

读取一个文件,给定一个字符串,判断这个字符串在文件中出现的次数,面试笔试经常遇到的问题

public class CountStringTest {
    
    public static void main(String[] args) {
        try {
            //统计E盘下面test.txt中的q字符出现的次数
            System.out.println("E盘下面test.txt中的q字符出现的次数为:");
            System.err.println(count("E:\\test.txt", "q"));
           } catch (FileNotFoundException e) {
            e.printStackTrace();
           } catch (IOException e) {
            e.printStackTrace();
           }

    }
     public static int count(String filename, String target)throws FileNotFoundException, IOException {
               FileReader fr = new FileReader(filename);
               BufferedReader br = new BufferedReader(fr);
               StringBuilder strb = new StringBuilder();
               while (true) {
                String line = br.readLine();
                if (line == null) {
                 break;
                }
                strb.append(line);
               }
               String result = strb.toString();
               int count = 0;
               int index = 0;
               while (true) {
                index = result.indexOf(target, index + 1);
                if (index > 0) {
                 count++;
                }else {
                 break;
                }
               }
               br.close();
               return count;
     }
}

技术分享图片

 

读取一个文件,给定一个字符串,判断这个字符串在文件中出现的次数

原文:https://www.cnblogs.com/xiangpeng/p/9523530.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!