java字符串数组进行大小排序

若是将两个字符串直接比较大小,会包: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

posted @ 2016-08-31 14:18  凭栏独倚  阅读(23999)  评论(0编辑  收藏  举报