您的位置:首页 > 编程语言 > Java开发

JAVA实现 计算txt文件中特定单词个数

2014-12-09 22:53 316 查看
如下a.txt文件所示,计算文件中"hello"单词的个数

hello abd the do me hello you are hello

实例代码:

package com.mian;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class FindWord {

public static void main(String[] args) {
// TODO Auto-generated method stub
//find the word "hello"
FindWord findWor = new FindWord();
String strDir = "a.txt";
int count = 0;
try {
count = findWor.findWord(strDir,"hello");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(count);
}

public int findWord(String str,String key) throws IOException,Exception{
int count = 0;
BufferedReader br = new BufferedReader(new FileReader(str));
StringBuffer sb = new StringBuffer();
String str1;
while((str1=br.readLine())!=null){
sb.append(str1);
}
List strList = new ArrayList();
StringTokenizer st = new StringTokenizer(sb.toString(),",.! \n");
while(st.hasMoreTokens()){
strList.add(st.nextToken());
}
System.out.println(strList.size());
for(int i=0;i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: