Java:从文件中为存储到数组中的每个单词增加wordCount

时间:2018-06-05 03:43:00

标签: java

我尝试读取文件并将文件中的单词存储到不包含空格/多个空格的字符串数组中。例如。我的文件有"这是一个测试",程序应该存储到一个数组arr ["这","是"," a&# 34;," test"]并且每次将一个单词存储到数组中时也会增加一个名为wordCount的变量。

我明白我可以使用

fileContents.split("\\s+")

但是每次将word添加到数组中时,它都不会增加wordCount。我认为for循环会完成这项工作,但我不知道如何。

感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:1)

您可以迭代拆分调用的结果,并在同一次迭代中向字数添加一个:

        String fileContents = "this is a test";
        int wordCount = 0;
        for (String word: fileContents.split("\\s+")) {
            System.out.println(word);
            wordCount++;
            System.out.println(wordCount);
        }

每次有新单词时,都应该在数组结构中添加存储空间。

答案 1 :(得分:0)

BufferedReader reader;
    try {
        reader = new BufferedReader(new FileReader(
                "/Users/pankaj/Downloads/myfile.txt"));
        String line = reader.readLine();
        int count = 0;
        while (line != null) {
            String[] array = line.split("\\s+");
            count = count + array.length;
            line = reader.readLine();
        }
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

在这里,我逐行获取,以便您可以为每行添加其他功能。还可以通过计数变量获取计数。