问题+代码:
创建一个长度是8的字符串数组
使用8个长度是5的随机字符串初始化这个数组
对这个数组进行排序,按照每个字符串的首字母排序(无视大小写)
注1: 不能使用Arrays.sort() 要自己写
注2: 无视大小写,即 Axxxx 和 axxxxx 没有先后顺序
toLowerCase() 方法用于将大写字符转换为小写。
toCharArray() 方法将字符串转换为字符数组。
charAt()方法获取某位置字符
getchars(start,end,目标字符串,起始位置0或者其他数字);
package Fengzhaung;
import java.util.Arrays;
import java.util.Random;
public class demoo1 {
public static void main(String[] args) {
Random random=new Random();
String[] str=new String[8];
for (int i = 0; i <8; i++) {
char c[]=new char[5] ;
for (int j = 0; j <5 ; j++) {
char temp;
if(random.nextInt(2)==0){
temp=(char)(random.nextInt(26)+65);
}
else
temp=(char)(random.nextInt(26)+97);
c[j]=temp;
}
str[i]=new String(c);
}
System.out.println(Arrays.toString(str));
System.out.println("排序好后的字符串数组是:");
for (int i = 0; i < 8; i++)
{
int min = i;
for (int j = i; j < 8; j++){
if(Character.toLowerCase(str[j].toCharArray()[0])<
Character.toLowerCase(str[min].toCharArray()[0]))
min=j;
}
String temp = str[i];
str[i] = str[min];
str[min] = temp;
}
System.out.println(Arrays.toString(str));
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/3f2b720885e7479ca63363056c2b8669.png)
这样写也行:
for (int j = i; j < 8; j++){
// if(Character.toLowerCase(str[j].toCharArray()[0])<
// Character.toLowerCase(str[min].toCharArray()[0])) //比较第一个字母
// min=j;
if(Character.toLowerCase(str[j].charAt(0))<Character.toLowerCase(str[min].charAt(0)))
min=j;
}`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)