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
  • 相关阅读:
    把字符串输入到表格里
    x 的 x 次方等于10,求 x
    java 中 二进制串与浮点数的相互转化
    堆栈 Objective-C NSString copy strong
    c一些学习过程中突然错过的细节
    视图控制器
    名词从句
    FastDFS
    Python
    http 提交表单数据
  • 原文地址:https://www.cnblogs.com/xiangpeng/p/9523530.html
Copyright © 2011-2022 走看看