有几个数字 如“1,23,2,43,67,34”是用逗号分开的,现在要将它们进行降序排列并输出,要求不能使用split()方法?

解决方案 »

  1.   


    String str="1,23,2,43,67,34";
         Pattern p=Pattern.compile(",");
         Matcher m=p.matcher(str);
         int beginpos=0;
         List<String> list=new ArrayList<String>();
         while(m.find()){
         list.add(str.substring(beginpos, m.end()-1));
         beginpos=m.end();
         }
         Collections.sort(list,new Comparator<String>(){
    public int compare(String o1, String o2) {
    int a=Integer.parseInt(o1);
    int b=Integer.parseInt(o2);
    if(a>b)
    return -1;
    else if(a==b)
    return 0;
    else 
    return 1;
    }
        
         });
         System.out.println(list);
        }
    }破题,有split不让用。
      

  2.   

    public static void sort()
    {
    String str = "12,3,423,25,1,53";

    //计算  ‘,‘ 号的个数;
    int sum=0;
    for(char c:str.toCharArray())
    {
    if(c==',')
    {
    sum++;
    }
    }

    System.out.println(sum);

    String[] aaa = new String[]{};
    SortedSet tr=new TreeSet();

    for(int i=0;i<sum;i++)
    {
    String s=str.substring(0, str.indexOf(","));
    int b=Integer.parseInt(s);
    str=str.substring(str.indexOf(',')+1);
    tr.add(b);
    }
    System.out.println(tr);
    }楼上的兄台很强