星空网 > 软件开发 > Java

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 keys15    * @return16    * */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 pre36    * @param next37    * @return38    * */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




原标题:java字符串数组进行大小排序

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

类别排名第一!这款奇异的圣诞节产品大受欢迎:https://www.ikjzd.com/articles/136552
新手卖家应该避开的13个选品方向:https://www.ikjzd.com/articles/136553
香港公司怎么注销?要什么条件?:https://www.ikjzd.com/articles/136554
当独立站遇上TikTok,抓住东南亚电商新红利:https://www.ikjzd.com/articles/136555
这几款拼图版权侵权了!:https://www.ikjzd.com/articles/136556
亚马逊卖家如何有效优化亚马逊站内PPC广告?:https://www.ikjzd.com/articles/136557
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
北京丰台区水上乐园哪家好玩?:https://www.vstour.cn/a/366177.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流