簡體   English   中英

查找文件中最長單詞出現的行號

[英]Find the line numbers at which the longest word appears in a file

您好,我需要找到文件中最長單詞出現的行號。 如果存在兩個或兩個以上相同最長長度的單詞,則僅跟蹤第一個。 我已經完成了最長單詞的跟蹤,但是我需要幫助來找到最長單詞所在的行。這是我找到最長單詞的代碼:

        while(scan2.hasNextLine()){
            String line = scan2.nextLine();
            if(line.contains(longestWord)){
                longestWordList.add(longestWord);
            }
            else{
                longestWordList.add(null);
            }
        }

您需要跟蹤當前的行號,最長的單詞的行號和最長的單詞的長度。 對於每一行,通過在空格和標點符號上進行拆分,將行拆分為單詞數組。 您可以使用正則表達式執行此操作。 然后查看每個單詞是否長於最長單詞。 如果找到了新的最長單詞,請記錄當前行號並記錄新的最長單詞長度。

int lineNumLongest = 0, lineNumCurrent = 0, longestLength = 0;
while(scan2.hasNextLine()) {
    lineNumCurrent++;
    String[] words = scan2.nextLine().split("[ .?!,;:/\\\\]");
    for (String word : words) {
        if (word.length() > longestLength) {
            lineNumLongest = lineNumCurrent;
            longestLength = word.length();
        }
    }
}

暫無
暫無

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

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