Random string array sort

Requirement: Create a string array
of length 8 Initialize the array with 8 random strings of length 5
Sort the array according to the first letter of each string (ignoring case)
Note 1: Arrays cannot be used .sort() should be written by yourself
Note 2: Ignore case, that is, Axxxx and axxxxx are in no order

	String s[] = new String[8];	
		//用来存放8句字符串的
	char []b = new char[5];
	
	int i ;
	int j;
	char []ch = new char[5];	
	for( j=0;j<s.length;j++)		//随机生成8组长度为5的字符数组
	{
		char []ch1 = new char[5];	//这句话很重要!!! 最开始在想的是如何将字符数组的数组换成字符串
		//也就是每次循环产生新的字符数组来接受随机数或字母
		for( i=0;i<ch1.length;i++) {
			while(true)
			{
				b[i] = (char)(Math.random()*126);
				if (Character.isLetter(b[i])||Character.isDigit(b[i]))
				{
					ch1[i] = b[i];
					break;
				}
				else 
					continue;
				
			}
		}
		s[j] = String.copyValueOf(ch1);
	}
	
	
	System.out.println("排序前的字符串数组:     ");
		System.out.println(Arrays.toString(s));
		for(j=0;j<s.length-1;j++)
		{
			for(i=j+1;i<s.length;i++)
			{
				if(Character.toUpperCase(s[j].charAt(0))>Character.toUpperCase(s[i].charAt(0)))	//将首字母全部转化为大写
				{
					String temp = s[i];					//选择法排序,通过i和i+1进行比较来得出顺序   左侧一切==一句Arrays.sort(s); 哎!
					s[i] = s[j];
					s[j] = temp;
				}
			}
		}
	
    System.out.println("排序后的字符串数组:");
    System.out.println(Arrays.toString(s));		//批量输出字符串数组的长度,这个方法值得记一下
    }			

}
// String array before sorting:
// [qSNSj, Fihhm, JEow5, CHOh2, WFLf0, 5r4ZZ, 2NRxo, xxdWQ]
// Sorted string array:
// [2NRxo, 5r4ZZ, CHOh2, Fihhm, JEow5 , WFLf0, qSNSj, xxdWQ]

Guess you like

Origin blog.csdn.net/weixin_45729934/article/details/105414854