Java随机生成字符串存入数组中按首字母大小排序

import java.util.Arrays;

/*
 * 生成随机字符串长度为5存放在长度为8的数组中,字符串生成范围是数字,大小写字母
按首字母按ASCII码大小有小到大排序但大小写字母排序不分前后。
 */
public class TestNumString {
public static void main(String[] args) {
	//定义存放字符的数组
	String[] StrArray = new String[10];
	 for (int i = 0; i < StrArray.length; i++) {
         String randomString = rr(5);
         StrArray[i] = randomString;
     }
     System.out.println("未排序前的字符串数组:");
     System.out.println(Arrays.toString(StrArray));
     
     //冒泡排序
     for (int j = 0; j < StrArray.length; j++) {
         for (int i = 0; i < StrArray.length - j - 1; i++) {
             char Char1 = StrArray[i].charAt(0);  //charAt()方法获取字符串的首字母
             char Char2 = StrArray[i + 1].charAt(0);
             Char1 = Character.toUpperCase(Char1);//把首字母都变为大写
             Char2 = Character.toUpperCase(Char2);

             if (Char1 > Char2) {
                 String temp = StrArray[i];
                 StrArray[i] = StrArray[i + 1];
                 StrArray[i + 1] = temp;
             }
         }
     }

     System.out.println("排序后的字符串数组:");
     System.out.println(Arrays.toString(StrArray));
	
}

//生成字符串的方法

private static String rr(int length) 
{
char[] charArray = new char[length];
short start = (short)'0';   //0的ASCII码是48
short end = (short)'z';    //z的ASCII码是122(0到z之间有特殊字符)
for (int i = 0; i < length; i++) {
	while(true)
	{
		char cc1 = (char)((Math.random()*(end-start))+start);
		if(Character.isLetterOrDigit(cc1))  //判断字符是否是数字或者字母
		{
			charArray[i] = cc1;
			break;
		}	
	}
}
String StringRes = new String(charArray);//把字符数组转化为字符串
return StringRes;
}

}

©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页