讀取一個文件,給定一個字符串,判斷這個字符串在文件中出現的次數


讀取一個文件,給定一個字符串,判斷這個字符串在文件中出現的次數,面試筆試經常遇到的問題

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM