在文本文件中查找特定单词并计算它 [英] Find specific word in text file and count it

查看:25
本文介绍了在文本文件中查找特定单词并计算它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我写代码吗?如何在文本文件中搜索任何单词并计算重复的次数?

someone can help me with code? How to search in text file any word and count how many it were repeated?

例如test.txt:

For example test.txt:

hi
hola
hey
hi
bye
hoola
hi

如果我想知道 test.txt 中的单词Hi"重复了多少次,程序必须说重复 3 次"

And if I want to know how many times are repeated in test.txt word "Hi" program must say "3 times repeated"

我希望你明白我想要什么,谢谢你的回答.

I hope you understood what I want, thank you for answers.

推荐答案

public int countWord(String word, File file) {
int count = 0;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
    String nextToken = scanner.next();
    if (nextToken.equalsIgnoreCase(word))
    count++;
}
return count;
}

这篇关于在文本文件中查找特定单词并计算它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆