给字符串数组排序

字符串由多个数字字符串和空格组成,如:
String str="99 345 8 888 55 0 -9999 30";
请编写函数sortNumStr,将字符串中数字字符串按数值大小升序排序,组成新的字符串:
public static String sortNumStr(String numStr)
例如,以上例中的str作为参数,返回结果:
"-9999 0 8 30 55 99 345 888"

 

 1 package test.string;
 2 
 3 import java.util.Arrays;
 4 import java.util.StringTokenizer;
 5 
 6 public class SortNumStr {
 7     
 8     public static String sortNumStr(String numStr){
 9         StringTokenizer numString = new StringTokenizer(numStr);
10         String[] results = new String[numString.countTokens()];
11         int count = 0;
12         while(numString.hasMoreTokens()){
13             results[count++] = numString.nextToken();
14         }//分割字符串
15         int[] i = new int[results.length];
16         for(count = 0; count < results.length; count++){
17             i[count] = Integer.parseInt(results[count]);
18             }//将字符串类型转换成数字类型
19         Arrays.sort(i);//排序
20         StringBuffer str = new StringBuffer();
21         for(count=0;count<results.length;count++){
22             str.append(i[count]+"  ");
23         }//将数组转换成字符串
24         return str.toString();
25     }
26     
27     public static void main(String[] args){
28         String str = "99 345 8 888 55 0 -9999 30";
29         System.out.println("The sorted numbers:"+sortNumStr(str));
30         }
31     }

 

转载于:https://www.cnblogs.com/hustxjtu/archive/2013/01/26/2877695.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值