题目:随机生成一段数字和字符混合的字符串,例如:J,X,87,19,A,Q,M,K,49,30,J,47,P,B,41,63,然后分别把数字和字母进行排序?- import java.util.Random;
- public class java01{
- public static void main(String[] args){
- String s = method();
- method_1(s);
- }
- /*生成一个随机字符串*/
- public static String method(){
- Random random = new Random();
- String str = "";
- for(int i=0;i<100;i++){
- int ran = random.nextInt(2);
- if(1==ran){
- int sum = random.nextInt(100);
- if(99!=i){
- str+=sum+",";
- }else{
- str+=sum;
- }
- }else{
- char ch = (char) (random.nextInt(26)+'A');
- if(99!=i){
- str+=ch+",";
- }else{
- str+=ch;
- }
- }
- }
- return str;
- }
-
- /*把字符串中的数字和字母进行分离,分别存入数组strArr2和strArr1中*/
- public static void method_1(String str){
- String[] strArr1 = new String[100];
- int[] strArr2 = new int[100];
- int count1 = 0;
- int count2 = 0;
- String[] strArr = str.split(",");
- for(int i=0;i<strArr.length;i++){ // k,34,j,k,5,j,4,k,6l,j,5,k,7,l
- if(strArr[i].compareTo("A")>=0 && strArr[i].compareTo("Z")<=0){
- strArr1[count1++] = strArr[i];
- }else{
- strArr2[count2++] = Integer.parseInt(strArr[i]);
- }
- }
-
- /*对字符进行排序*/
- for(int i=0;i<count1-1;i++){
- for(int j=i+1;j<count1;j++){
- if(strArr1[i].compareTo(strArr1[j])>0){
- String temp;
- temp = strArr1[i];
- strArr1[i] = strArr1[j];
- strArr1[j] = temp;
- }
- }
- }
-
- /*对数字进行排序*/
- for(int i=0;i<count2-1;i++){
- for(int j=i+1;j<count2;j++){
- if(strArr2[i]>strArr2[j]){
- int temp;
- temp = strArr2[i];
- strArr2[i] = strArr2[j];
- strArr2[j] = temp;
- }
- }
- }
-
- /*打印随机生成字符串*/
- System.out.println("随机生成字符串:");
- for(int i=0;i<strArr.length;i++){
- System.out.print(strArr[i]+" ");
- }
- System.out.println();
-
- /*把排序后的数字和字符放到原来位置*/
- count1 = 0;
- count2 = 0;
- for(int i=0;i<strArr.length;i++){
- if(strArr[i].compareTo("A")>=0 && strArr[i].compareTo("Z")<=0){
- strArr[i] = strArr1[count1++];
- }else{
- strArr[i] = strArr2[count2++]+"";
- }
- }
-
- /*打印排序后字符串*/
- System.out.println("排序后字符串:");
- for(int i=0;i<strArr.length;i++){
- System.out.print(strArr[i]+" ");
- }
- }
- }
复制代码 |