簡體   English   中英

如何創建一個字符串數組來存儲.txt文件中“字典”的單詞?

[英]How to make an array of Strings to store words of a “dictionary” from a .txt file?

我需要制作一個字典 ,從.txt文件中提取單詞。 這些單詞(逐行分隔)需要存儲在String數組中。 我已經知道要分開單詞並將它們添加到新的.txt文件中,但是我不知道如何將它們分別添加到String數組中。

您需要計算文件中的行數。 創建一個該大小的數組

然后,對於文件中的每一行, 讀取它並將其插入數組中的index[lineReadFrom]

由於不允許使用ArrayListLinkedList對象,因此建議您在讀取輸入文件時“即時”保存找到的每個單詞。 您可以按照以下一系列步驟來完成此操作:

1.逐行讀取文件:使用常見的new BufferedReader(new FileInputStream("/path/to/file"))方法並逐行讀取(因為我假設您已經在做,請查看代碼)。

2.檢查每一行是否有單詞:String.split()將每個possilbe單詞用空格String.split()並刪除標點符號。

3.保存每個單詞:遍歷String.split()返回的String數組,對於您認為一個單詞的每個元素,使用通用的new BufferedWriter(new FileWriter("")).write(...);

4.關閉您的資源:遍歷資源后,最好是在finally塊中,關閉讀者的作家。

這是完整的代碼示例:

public static void main(String[] args) throws IOException {
    File dictionaryFile = new File("dict.txt");

    // Count the number of lines in the file
    LineNumberReader lnr = new LineNumberReader(new FileReader(dictionaryFile));
    lnr.skip(Long.MAX_VALUE);

    // Instantiate a String[] with the size = number of lines
    String[] dict = new String[lnr.getLineNumber() + 1];
    lnr.close();

    Scanner scanner = new Scanner(dictionaryFile);
    int wordNumber = 0;

    while (scanner.hasNextLine()) {
        String word = scanner.nextLine();
        if (word.length() >= 2 && !(Character.isUpperCase(word.charAt(0)))) {
            dict[wordNumber] = word;
            wordNumber++;
        }
    }
    scanner.close();
}

完成對118,620行文件的執行大約需要350 ms ,因此它應該可以滿足您的目的。 請注意,我在開始時實例化了數組,而不是在每一行上都創建了一個新的String[] (並像在代碼中一樣替換了舊的)。

我使用wordNumber來跟蹤當前的數組索引,以便將每個單詞添加到數組的正確位置。

我還使用.nextLine()而不是.next()因為您說字典是用行而不是用空格分隔的( .next()使用的是字典)。

暫無
暫無

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

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