按长度排序,然后按字母顺序排序 [英] sort words by length and then by alphabetical order
问题描述
下面你可以看到我的代码。它从字典中读取单词并将与特定patern匹配的单词复制到test.txt。我的问题是如何首先通过LENGTH对test.txt中的单词进行排序,以及何时按长度排序,然后按字母顺序排序。例如。
Below you can see my code. It reads words from dictionary and copy words that match specific patern to test.txt. My qusetion is how to sort words in test.txt first by LENGTH and when they are sorted by length then by alphabetical order. For example.
我有:
- car
- 鼠标
- 数字
- abc
- grs
- car
- mouse
- number
- abc
- grs
我需要什么
- abc
- car
- grs
- mouse
- number
- abc
- car
- grs
- mouse
- number
我的清单包含超过10000字。
My list contains over 10000 words.
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Pattern;
public class moja {
public static void main(String[] args) {
try {
File file = new File("SloveneLexicon.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(
new FileInputStream(file), "UTF8"));
String vrstica;
File test = new File("test.txt");
FileWriter fw = new FileWriter(test);
while ((vrstica = bufferedReader.readLine()) != null) {
String s = vrstica;
String[] dobi_besedo_v_vrstici = s.split("\\s+");
String prva_beseda = dobi_besedo_v_vrstici[0];
String tretja_beseda = dobi_besedo_v_vrstici[2];
String nova_vrstica = System.getProperty("line.separator");
Pattern ena = Pattern.compile("S\\p{L}\\p{L}ei\\p{L}*");
if(ena.matcher(tretja_beseda).matches()){
fw.write(prva_beseda+nova_vrstica);
fw.write("\n");}
Pattern dva = Pattern.compile("P\\p{L}\\p{L}\\p{L}ei\\p{L}*");
if(dva.matcher(tretja_beseda).matches()){
fw.write(prva_beseda+nova_vrstica);
}
}
fw.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
推荐答案
您应该定义一个Comparator,以便以正确的方式比较两个字符串。在您的情况下,较短的字符串将在较长的字符串之前;如果大小相等 - 顺序是字母。
然后你使用这个比较器进行排序 - 使用 Collections.sort()
。
You should define a Comparator, so that it compares the two strings in a right manner. In your case, the shorter string will go prior to a longer string; if sizes are equal - the order is alphabetic.
Then you use this Comparator to do the sorting - use Collections.sort()
for it.
这篇关于按长度排序,然后按字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!