简体   繁体   English

需要按字母顺序排列文本文件中的单词

[英]Need to arrange the words in a text file in alphabetical order

I have a text file full of words that I need to arrange into alphabetical order. 我有一个充满单词的文本文件,需要按字母顺序排列。 What are the steps I should take to do this. 我应该采取什么步骤来做到这一点。 I know I need to use an array but then put them in order and print it but I'm not sure of the exact details. 我知道我需要使用一个数组,然后将它们按顺序排列并打印出来,但是我不确定确切的细节。 Also I dont know how to read each individual string becuase I only know .nextLine which takes all the strings in a line. 另外我也不知道如何读取每个单独的字符串,因为我只知道.nextLine,它接受一行中的所有字符串。

Been working on this for a while and not making much progress any help would be greatly appreciated. 经过一段时间的努力并且没有取得太大进展,任何帮助将不胜感激。

You need to create a "global" list (not an array since you don't know the length) to hold the words and then read each line. 您需要创建一个“全局”列表(因为您不知道长度而不是数组)来保存单词,然后读取每一行。 Split each line into an array of words and then add them to this global list. 将每一行拆分为一个单词数组,然后将它们添加到此全局列表中。 Then sort this list. 然后对该列表进行排序。

Here is an example of a basic implementation of this: 这是此基本实现的示例:

Scanner scanner = new Scanner(file);
ArrayList<String> allWords = new ArrayList();
while (scanner.hasNextLine()) {
   String line = scanner.nextLine();
   String[] words = line.split(" ");
   List<String> wordList = Arrays.asList(words)
   allWords.addAll(wordList);             
}
scanner.close();
Collections.sort(allWords);

Note that I wrote this freehand so there may be syntax or even logic errors. 请注意,我写了这本徒手画,所以可能会有语法甚至逻辑错误。 Hopefully it gives you the basic road ahead though. 希望它能给您前进的基本道路。 Also, I didn't handle exceptions. 另外,我没有处理异常。

Hope this helps. 希望这可以帮助。 Please ask more questions, and good luck with your Java learning! 请问更多问题,祝您学习Java顺利!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM