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

}
 

 

转载于:https://www.cnblogs.com/ltb6w/p/8214623.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值