在Java中,对每行有多个单词并用换行符分隔的字符串进行排序的最佳方法是什么



我有一份我现在正在观看的动漫列表,我想按字母顺序对它们进行排序。下面是列表的一个小例子,共有200多行。我把它们都存储在一个文本文件中。我只是想要一种算法,可以用来对这类字符串进行排序。

此外,动漫的名字是日语的,所以它们可以包含特殊的字符和数字。

如果每行只有一个单词,那么我可以很容易地使用桶排序或基数排序,但问题是每行有多个单词,这些单词不应该排序。

例如,不应该对"蓝色驱魔器"进行排序,否则它将变成"驱魔器蓝色",甚至其中的字母也可能根据您使用的算法进行排序。

One piece
Naruto/naruto shippuden
Bleach
Fullmetal alchemist brotherhood
Fate/stay night
Fairy tale
Blue exorcist
Soul eater
Death note
Code geass: lelouch of the rebellion r1 and r2
Gurren lagann

这是我的代码

public static String[] ReadFileToCharArray (String filePath)
        throws IOException
{
    StringBuilder fileData = new StringBuilder(1000);
    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    String[] test = new String[1000];
    for (int i = 0; i <= 105; i++)
    {
        test[i] = reader.readLine();
    }
    reader.close();
    return test;
}
public static void main (String args[]) throws IOException
{
    String[] test = new String[10000];
    String path = "anime.txt";
    Files files = new Files();
    test = files.ReadFileToCharArray(path);
    Arrays.sort(test); // <----------ERROR at line 12
    System.out.println("test " + test);
    files.writetofiles(test);
}

错误

Exception in thread "main" java.lang.NullPointerException
    at java.util.ComparableTimSort.binarySort(ComparableTimSort.java:232)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:176)
    at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
    at java.util.Arrays.sort(Arrays.java:472)
    at Main.main(Main.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

问题是每行有多个单词,这些单词不应该排序。

如果我理解正确,你可以逐行阅读文件(而不是逐字逐句):

List<String> names = new ArrayList<>();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
    names.add(line);
}
br.close();
Collections.sort(names);
// TODO write names to file

如果你使用的是Linux,你也可以只使用sort:

sort fileName > fileNameSorted

最新更新