String
我需要按升序对以下数组进行排序。
String str[] = {"ASE", "LSM", "BSE", "LKCSE", "DFM"};
怎么做?我需要帮助。
String
我需要按升序对以下数组进行排序。
String str[] = {"ASE", "LSM", "BSE", "LKCSE", "DFM"};
怎么做?我需要帮助。
此答案基于Signare和HeartBeat的建议。浏览此链接了解详情。另外这个链接,使用 java.util.Array 排序可能会有所帮助。
// Initialization of String array
String strs[] = {"One", "Two", "Threee", "Four", "Five", "Six", "Seven"};
// implementation of Comparator
Comparator strComparator = new Comparator() {
public int compare(Object o1, Object o2) {
return o1.toString().compareTo(o2.toString());
}
};
// Sort
Arrays.sort(strs, strComparator);
Here is my solution:-
String str[]={"ASE","LSM","BSE","LKCSE","DFM"};
for(int j = 0; j < str.length; j++){
for(int i = j + 1; i < str.length; i++) {
if(str[i].compareTo(str[j]) < 0) {
String t = str[j];
str[j] = str[i];
str[i] = t;
}
}
}
尝试这个 -
import java.util.*;
import java.io.*;
public class TestSort1 {
String [] words = { "Réal", "Real", "Raoul", "Rico" };
public static void main(String args[]) throws Exception {
try {
Writer w = getWriter();
w.write("Before :\n");
for (String s : words) {
w.write(s + " ");
}
java.util.Arrays.sort(words);
w.write("\nAfter :\n");
for (String s : words) {
w.write(s + " ");
}
w.flush();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
// useful to output accentued characters to the console
public static Writer getWriter() throws UnsupportedEncodingException {
if (System.console() == null) {
Writer w =
new BufferedWriter
(new OutputStreamWriter(System.out, "Cp850"));
return w;
}
else {
return System.console().writer();
}
}
}