String比较排序

public class StringCom {


/**
* "avf ggh f tt dgh acd ac dg gh kl kmn" 排序
*/
public static void main(String[] args) {
String s = "avf ggh f tt dgh acd ac dg gh kl kmn";
String[] s1 = s.split(" ");
for(int i=0; i<s1.length-1; i++){
for(int j=0; j<s1.length-1-i; j++){
if(doString(s1[j],s1[j+1]) > 0){
String tem = s1[j];
s1[j] = s1[j+1];
s1[j+1] = tem;
}
}
}
StringBuffer sb = new StringBuffer();

for(int i=0; i<s1.length; i++){
sb.append(s1[i]+" ");
}
System.out.println(sb);

}
public static int doString(String s1, String s2){
int len1 = s1.length(), len2 = s2.length();
int res  = len1 - len2;
int minlen = Math.min(len1, len2);
for(int i=0; i<minlen; i++){
if(s1.charAt(i) != s2.charAt(i)){
res = s1.charAt(i)-s2.charAt(i);
break;
}
}
return res;
}


}
2、题稍加难度


public class PaiXuString {


/**排序中还需将小写字母一起排序,如a 要在B,b前
* 字符串排序  如 Ac  Bc AcO ac   排序结果:Ac, AcO, ac, Bc
*/
public static void main(String[] args) {
String[] s = { "Bc","Ad","aC","cD","During","little","X man","day" };
String temp;
int l = s.length;
for(int i=0; i<l-1; i++){
for(int j=0; j<l-1-i;j++){
if(com(s[j],s[j+1]) > 0){
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
System.out.println(Arrays.toString(s));


}
public static int com(String s1, String s2){
int res = s1.length() - s2.length();
int len = Math.min(s1.length(),  s2.length());
int char1code = 0, char2code =0;
char[] Char1 = s1.toCharArray();
char[] Char2 = s2.toCharArray();
for(int i=0; i<len; i++){
if(Char1[i] != Char2[i]){
char1code = Char1[i]>96? Char1[i]-96 : Char1[i] -64;
char2code = Char2[i]>96? Char2[i]-96 : Char2[i] -64;
   if(char1code != char2code){
    res = char1code -char2code;
    break;
   }else {
    res = Char1[i] - Char2[i];
    break;
   }
}else{
continue;
}
}
return res;
}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值