若是將兩個字符串直接比較大小,會包:The operator > is undefined for the argument type(s) java.lang.String, java.lang.String的錯誤。
字符串比較大小可以用字符串長度或者是比較字符串內字符的ASCII碼值,前者太簡單,就不進行講述記錄。
字符串用ASCII碼比較大小,規則是:
1、比較首字母的ASCII碼大小
2、若是前面的字母相同,則比較之後的字母的ASCII碼值
3、若是一個字符串從首字母開始包含另一個字符串,則認為字符串長度較長的大;例 :abc > ab
備注:代碼中使用commons-logging-1.2.jar,排序從小到大
1 import org.apache.commons.logging.Log;
2 import org.apache.commons.logging.LogFactory;
3
4 /**
5 * 對字符串數組進行排序
6 * @author panjianghong
7 * @since 2016/8/31
8 * */
9 public class StringSort {
10
11 private static final Log _log = LogFactory.getLog(StringSort.class);
12 /**
13 * 對字符串數組進行排序
14 * @param keys
15 * @return
16 * */
17 public static String[] getUrlParam(String[] keys){
18
19 for (int i = 0; i < keys.length - 1; i++) {
20 for (int j = 0; j < keys.length - i -1; j++) {
21 String pre = keys[j];
22 String next = keys[j + 1];
23 if(isMoreThan(pre, next)){
24 String temp = pre;
25 keys[j] = next;
26 keys[j+1] = temp;
27 }
28 }
29 }
30 return keys;
31 }
32
33 /**
34 * 比較兩個字符串的大小,按字母的ASCII碼比較
35 * @param pre
36 * @param next
37 * @return
38 * */
39 private static boolean isMoreThan(String pre, String next){
40 if(null == pre || null == next || "".equals(pre) || "".equals(next)){
41 _log.error("字符串比較數據不能為空!");
42 return false;
43 }
44
45 char[] c_pre = pre.toCharArray();
46 char[] c_next = next.toCharArray();
47
48 int minSize = Math.min(c_pre.length, c_next.length);
49
50 for (int i = 0; i < minSize; i++) {
51 if((int)c_pre[i] > (int)c_next[i]){
52 return true;
53 }else if((int)c_pre[i] < (int)c_next[i]){
54 return false;
55 }
56 }
57 if(c_pre.length > c_next.length){
58 return true;
59 }
60
61 return false;
62 }
63
64
65 public static void main(String[] args) {
66
67 String[] keys = getUrlParam(new String[]{"fin","abc","shidema","shide","bushi"});
68
69 for (String key : keys) {
70 System.out.println(key);
71 }
72
73 }
74 }
控制台打印結果為:
abc
bushi
fin
shide
shidema