zoukankan      html  css  js  c++  java
  • 读取一个文件,给定一个字符串,判断这个字符串在文件中出现的次数

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

    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;
         }
    }

    yian
  • 相关阅读:
    奔跑的绵羊js
    13.差分
    12.子矩阵的和
    11.前缀和
    10.高精度除法
    9.高精度乘法
    8.高精度减法
    7.高精度加法
    6.数的三次方根
    5.数的范围
  • 原文地址:https://www.cnblogs.com/xiangpeng/p/9523530.html
Copyright © 2011-2022 走看看