/**
* Name: 比较两个字符串大小
* Description: 比较的规则和数据库中的order by效果一致;
* null自动转为空,空字符串最大;
*
* @param first 要比较的第一个字符串;
* second 要比较的第二个字符串;
* @return first大于second返回正数;
* first等于second返回0;
* first小于second返回负数;
* 内部异常默认返回0;
* 返回值非固定值哦~~;
* @throws
* @Author 杨元
*/
public static int compareString(String first,String second){
int result = 0;
try{
//null转空
first = first==null?"":first;
second = second==null?"":second;
//预先记录字符串长度,避免反复读取
int firstLength=first.length();
int secondLength=second.length();
//处理含有空串的特殊情况
if("".equals(first) || "".equals(second)){
//谁长谁小
result = secondLength-firstLength;
}else{
//临时空间,用来存放ascii码总和
int firstCount = 0;
int secondCount = 0;
//用纯运算得出两个数中较小的数,实在是bt
int minLength = (secondLength*(firstLength/secondLength) + firstLength*(secondLength/firstLength))/(firstLength/secondLength + secondLength/firstLength);
//按两个字符串中较短的位数去逐位截取,防止越界
for(int i=0;i<minLength;i++){
//求ascii码和
firstCount+=first.substring(i,i+1).getBytes()[0];
secondCount+=second.substring(i,i+1).getBytes()[0];
//和不相等,说明已经比较出了大小
if(firstCount!=secondCount){
break;
}
}
if(firstCount==secondCount){
//长度长的大
result = firstLength-secondLength;
}else{
//总和大的大
result = firstCount-secondCount;
}
}
}catch (Exception e) {}
return result;
}
新闻热点
疑难解答