当前位置:网站首页>Data sorting in string

Data sorting in string

2022-07-07 20:24:00 Bear Bibi

demand : There's a string :“91 27 46 38 50”, Please write a program to achieve the final output :“27 38 46 50 91”

analysis :
The first step is to separate the numbers in the string ( According to the space ) Put it in an array ;
Step 2 sort the array ;
The third step is to sort and convert it into string splicing again ;

Split the string according to the space :https://blog.csdn.net/yezonghui/article/details/106455940

Concrete realization :

  1. Define a string
  2. Store the numeric data in the string into a int In an array of types ;
    public String[] split(String regex) : Get every digital data
    public static int parseInt(String) : Store every data in int Array
  3. Yes int Array to sort ;
  4. The sorted array elements are spliced to get a string
    use StringBuilder To realize ;
  5. Output results ;
package Integerr;

import java.util.Arrays;

public class StringSort {
    
    public static void main(String[] args) {
    
        
        String s = "91 27 46 38 50";    // 1
        String[] strArray = s.split(" "); // 2
        int[] intArr = new int[strArray.length];

        for (int i = 0; i < intArr.length; i++) {
    
            intArr[i] = Integer.parseInt(strArray[i]);
        }
        Arrays.sort(intArr); //3

        StringBuilder sb = new StringBuilder();   //4
        for (int i = 0; i < intArr.length; i++) {
    
            if (i == intArr.length - 1) {
    
                sb.append(intArr[i]);
            } else {
    
                sb.append(intArr[i] + " ");
            }
        }

        String s2 = new String(sb);   //5
        System.out.println(s2);
    }
}
原网站

版权声明
本文为[Bear Bibi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071814286044.html