繁体   English   中英

如何查看文本文件中存在多少次字符串数组中的单词

[英]How to see how many times words from string array are present in a text file

所以我想扫描一个文本文件,找出我的数组中的单词在该文本文件中使用的总次数。

使用我的代码,我只能找出在文本文件中找到数组中位置0的单词的次数。 我想要数组中所有单词的总数。

String[] arr = {"hello", "test", "example"};

File file = new File(example.txt);
int wordCount = 0;
Scanner scan = new Scanner(file);

for(int i = 0; i<arr.length; i++){
   while (scan.hasNext()) {
   if (scan.next().equals(arr[i])){
          wordCount++;
        }
 }
}
System.out.println(wordCount);

example.txt如下:

  hello hello hi okay test hello example test
  this is a test hello example

为此,我想要的结果是wordCount = 9

相反,我上面代码的wordCount等于4(文本文件中声明了hello的数量)

扫描文件中的行,然后扫描arr以查找匹配项...

try (Scanner scan = new Scanner(file)) {
    while (scan.hasNext()) {
        String next = scan.next()
        for(int i = 0; i<arr.length; i++){
            if (next.equals(arr[i])){
              wordCount++;
            }
        }
    }
}

这里发生的事情是:在第一个循环中,到达文件的末尾,你只得到'hello'的计数。 您可以在每个循环的结束/开始时重新调整指向文件开头的指针。


String[] arr = {"hello", "test", "example"};
File file = new File(example.txt);
int wordCount = 0;

for(int i = 0; i<arr.length; i++){
   Scanner scan = new Scanner(file);
   while (scan.hasNext()) {
   if (scan.next().equals(arr[i])){
          wordCount++;
        }
 }
}
System.out.println(wordCount);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM