Java 中統計文件中出現單詞的次數練習


 統計英文article.txt文件中出現hello這個單詞的次數

 這個是article.txt文件內容 {

   

hello The Royal Navy is trying hello to play hello down the problem,
after first trying to hide it. It is clearly embarrassing.
They have hello known about the problem for hello some time
but they did not hello want it hello to get in the way of the
commissioning hello ceremony hello in front hello of the Queen. hello

 

}

 

package ltb20180106;

import java.io.*;


public class WordCount  {
    
private File f;    
private BufferedReader br;
private BufferedWriter bw;
private String readline;
private int start=0;
private int end=0;
private int count=0;

    public WordCount() {
        
        try {
            
            f=new File("D:\\myRead\\article.txt");
            br=new BufferedReader(new FileReader(f));
            bw=new BufferedWriter(new OutputStreamWriter(System.out));
            
            
            while((readline=br.readLine())!=null) {
                
                    start=this.readline.indexOf("hello");
                     
                    if(start!=-1) { // 一行字符串中如果有hello出現就進行統計
                        
                        count++;
                        
                        end=this.readline.indexOf("hello",start+1);
                        
                        
                        
                        while(end!=-1) { //如果在這行中后續還有hello出現,繼續統計,直到末尾沒有hello出現為止。
                            
                            
                            count++; 
                            
                            System.out.print("[end:"+end+"]"+",");
                            
                             end=this.readline.indexOf("hello",end+1);
                             
                        }
                    }
                        
                     
                    bw.write(readline+"\r");
                    
                    System.out.println("累計總共的次數:【"+count+"】"+"start:【"+start+"】");
                    
                
                
                bw.flush();
            }
            
            System.out.println("單詞hello在文章【"+f.getName()+"】中出現的次數為:【"+count+"】");
            
            bw.close();
            
        }catch(Exception e) {
            
            e.getMessage();
        }
        
        
    }

    public static void main(String[] args) {
        
           new WordCount();
    }

}
 

 


免責聲明!

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



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