【发布时间】:2013-11-21 09:42:40
【问题描述】:
我有问题。 我想按字符串中的字符数对 txt 文件中的字符串进行排序 例如 输入: 啊啊啊 一个 啊 输出: 一个 啊 啊啊啊 我创建了包含按字母表排列的字符串的集合并创建了包含多个字符串字符的集合,但我无法理解
如何按字符串中的字符数排序
public class SortingFile {
public static void main(String[] args) throws IOException {
try{
File inputFile=new File("c:/a.txt");
Reader r=new FileReader(inputFile);
BufferedReader br=new BufferedReader(r);
List <String> list = new LinkedList<String>();
List <Integer> listLength= new LinkedList<Integer>();
String line=br.readLine();
list.add(line);
while (line!=null){
line=br.readLine();
list.add(line);
}
int arrsize=(list.size())-1;
System.out.println("line array size= "+arrsize);
list.remove(arrsize); //delete last element (he is null )
System.out.println("Before sorting by alphabet: "+list);
Collections.sort(list);//sorting by alphabet
System.out.println("After sorting by alphabet: " +list);
for (int i=0;i!=list.size();i++){ //add string lenght to collection
String a=list.get(i);
int aa=a.length();
listLength.add(aa);
}
System.out.println("lineLength:"+listLength);
Collections.sort(listLength); // sotring by asc
System.out.println("lineLength2:"+listLength);
br.close();
}catch (FileNotFoundException e1){
System.out.println("File ''a.txt'' Not Found :(");
e1.printStackTrace();
}
}
}
【问题讨论】:
标签: java string sorting numbers character