繁体   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