簡體   English   中英

Java:從文件存儲到數組的每個單詞的wordCount遞增

[英]Java: Incrementing wordCount for each word stored into array from file

我正在嘗試讀取文件,並將文件中的單詞存儲到一個字符串數組中(不包括空格/多個空格)。 例如,我的文件中有“ this is a test”這個詞,程序應將arr [“ this”,“ is”,“ a”,“ test”]存儲到數組中,並在每次存儲a時增加一個名為wordCount的變量字放入數組。

我知道我可以使用

fileContents.split("\\s+")

但這不會在每次將單詞添加到數組中時增加wordCount。 我在想for循環會完成這項工作,但我不知道如何做。

任何幫助表示贊賞。 謝謝。

您可以迭代split調用的結果,並在同一迭代中將單詞計數加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);
        }

每次有新單詞時,都應在數組結構中添加存儲。

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

在這里,我逐行獲取,因此您可以為每行添加其他功能。 還可以通過count變量獲取count。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM