- import java.lang.*;
- import java.util.Arrays;
- public class test {
- /**
- * 对一个字符串中的数值进行从小到大排列
- * “20 78 -9 -7 36 29”
- * @param args
- */
- private static final String SPACE_SEPARATOR=" ";
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- String numStr= "20 78 -9 -7 36 29";
- System.out.println(numStr);
- numStr=sortStringNumber(numStr);
- System.out.println(numStr);
- }
- public static String sortStringNumber(String numStr) {
- // TODO Auto-generated method stub
- String[] str_arr=stringToArray(numStr);
- int[] num_arr=toIntArray(str_arr);
- mySortArray(num_arr);
- String temp = arrayToString(num_arr);
- return temp;
- }
- public static String[] stringToArray(String numStr) {
- String[] str_arr=numStr.split(SPACE_SEPARATOR+"+");
- return str_arr;
- }
- public static String arrayToString(int[] num_arr) {
- // TODO Auto-generated method stub
- StringBuilder sb=new StringBuilder();
- for(int x=0;x<num_arr.length;x++){
- if(x!=num_arr.length-1)
- sb.append(num_arr[x]+SPACE_SEPARATOR);
- else
- sb.append(num_arr[x]);
- }
- return sb.toString();
- }
- public static void mySortArray(int[] num_arr) {
- // TODO Auto-generated method stub
- Arrays.sort(num_arr);
- }
- public static int[] toIntArray(String[] str_arr) {
- // TODO Auto-generated method stub
- int[] arr=new int[str_arr.length];
- for(int i=0;i<arr.length;i++){
- arr[i]=Integer.parseInt(str_arr[i]);
- }
- return arr;
- }
- }
复制代码
|
|