簡體   English   中英

計算文本文件中的空格以查找其字數

[英]Count spaces from text file to find its word count

我想創建一個從文本文件中讀取多行單詞的應用程序。 它將通過計算單詞之間的空格數並添加一個校正因子來輸出單詞計數。

我不確定要使用哪種輸入法。 我的當前代碼輸出不正確。 它不會計算第一個單詞之后的單詞,也不會計算空格。

我該如何解決?

public static void main(String[] args) throws IOException {

    Scanner in = new Scanner(new FileReader( "/input5.txt"));//file read


    System.out.println("Echo print of the input file is " + in.nextLine());

    int i = 0;
    int counter = 0;

    String a = in.next();
    while (in.hasNextLine()) {

        while (i < a.length()) {
            if (a.charAt(i) == ' ') {
                counter++;
            }
            i++;
        }
        i = 0;

    }

    int wordcount = (counter + 1);
    System.out.println("The word count is " + wordcount);
}

押注Aiwegfu24r; q0912j冷不是金錢,而是金錢Nil Nelzik1-aj

129puehilhwueildgyuol

表示輸入文件。

 public static void main(String[] args) throws IOException {
        int count = 0;

        Scanner in = new Scanner(new FileReader( "/input5.txt"));//file read
        while (in.hasNextLine()) {

            System.out.println("echo print of the input: " + in.nextLine());
            in.reset();
        }

        while (in.hasNext()) {

            count++;
            in.next();

        }
        System.out.println("The word count is " + count);

    }

那是新的代碼。

Scanner.next()的默認定界符為空格。 每次調用next()時,程序都會剝離空白並返回一個“單詞”。 因此,如果僅計算next()的調用次數,您可能會發現問題更容易:

Scanner in = new Scanner(new FileReader(dir + "/input5.txt"));
int count = 0;

while (in.hasNext()) {
    count++;
    in.next();
}

另外,請注意,在初始化計數循環之前,您正在調用nextLine()。 掃描程序對象具有內部緩沖區,並且每當您調用next()或nextLine()時,該緩沖區的光標就會向前移動。 您需要從程序中刪除對nextLine()的調用,或者需要重新初始化掃描儀。

如果要輸出文件內容(看起來確實如此),只需執行以下操作:

System.out.println("File contents:");
while (in.hasNextLine()) {
    System.out.println(in.nextLine());
}
in = new Scanner(new FileReader(dir + "/input5.txt"));
//now you can do your counting, as the buffer has been reset

怎么樣:

int count = 0;
while (in.hasNextLine())
    count += in.nextLine().trim().split("\\s+").length;

如果出現拆分,則正則表達式會占用多個空格,無論間距如何,都能為您提供正確的單詞數。

修剪命令將刪除前導空格(如果存在)。

您可以使用 -

public static int wordCount(String s) {
    int counter = 0;
    s = s.trim(); //edit

    for (int i = 0; i <= s.length() - 1; i++) {
        if (Character.isLetter(s.charAt(i))) {
            counter++;
            for (; i <= s.length() - 1; i++) {
                if (s.charAt(i) == ' ') {
                    counter++;
                }
            }

        }

    }
    return counter;
}

暫無
暫無

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

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