java 多个字符串首字母排序6_java经典试题:字符串按照首字母排序

2.32字符串排序

2.32.1题目:将字符串按照首字母排序,如果首字母相同则按照第二个字母排序……依次类推。

2.32.2 源程序

public class StringSort {

public static void main(String[] args) {

String temp = null;

String[] s = new String[5];

s[0] = "china".toLowerCase();

s[1] = "apple".toLowerCase();

s[2] = "MONEY".toLowerCase();

s[3] = "BOOk".toLowerCase();

s[4] = "yeah".toLowerCase();

/*

* for(int i=0; i

* if(s[i].compareToIgnoreCase(s[j]) > 0) { temp = s[i]; s[i] = s[j];

* s[j] = temp; } } }

*/

for (int i = 0; i < s.length; i++) {

for (int j = i + 1; j < s.length; j++) {

if (compare(s[i], s[j]) == false) {

temp = s[i];

s[i] = s[j];

s[j] = temp;

}

}

}

for (int i = 0; i < s.length; i++) {

System.out.println(s[i]);

}

}

static boolean compare(String s1, String s2) {

boolean result = true;

for (int i = 0; i < s1.length() && i < s2.length(); i++) {

if (s1.charAt(i) > s2.charAt(i)) {

result = false;

break;

} else if (s1.charAt(i) < s2.charAt(i)) {

result = true;

break;

} else {

if (s1.length() < s2.length()) {

result = true;

} else {

result = false;

}

}

}

return result;

}

}

2.32.3 运行结果:

apple

book

china

money

yeah

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值