簡體   English   中英

從文本文件中獲取所有單詞(Java)

[英]Get all words from text file (Java)

我正在嘗試顯示文件中可以水平和垂直找到的所有單詞,並且我正在嘗試打印每個單詞(行和列)的第一個字符的位置。

我讓它水平顯示每個單詞而不是垂直顯示。

這是我到目前為止使用的代碼

public class WordFinder {
    public static final String WORD_FILE = "words.txt";
    public static void find(){
        try {
            File file = new File(WORD_FILE);
            Scanner scanner = new Scanner(file);
            while (scanner.hasNext() == true) {
                String s = scanner.next();
                System.out.println(s);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
    }
}

它應該水平和垂直搜索文件以查找單詞。 一旦找到一個單詞,它應該顯示單詞的第一個字母的位置(EG grammar: row 8, position 1 )目前它只打印所有水平單詞。

您必須在迭代時計算單詞的行號和位置。 因此,您應該使用scanner.hasNextLine()scanner.nextLine() 之后,您可以拆分該行:

int lineNumber = 0;
while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    int positionNumber = 0;
    for (String word : line.split("\\s")) {
        if (!word.isEmpty())
            System.out.println(word + ": line " + (lineNumber + 1) + ", position " + (positionNumber + 1));
        positionNumber += word.length() + 1;
    }
    lineNumber++;
}

這將在所有空格 ( \\\\s ) 上拆分行並使用if (!word.isEmpty())處理雙空格(空詞if (!word.isEmpty())

暫無
暫無

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

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