按字符串里的数字排序

按字符串里的数字排序

给出的字符串结构是前边是字母、后边为数字,例如wew0145,要求给出一组数据,按照后边的数字从小到大排序。

输入

wr0068,lt01,qhy0027828,gh20425256,xj0033258,zmj00505562

输出

lt01,wr0068,qhy0027828,xj0033258,zmj00505562,gh20425256
 

 


//按字符串里的数字排序
// 输入 "wr0068,lt01,qhy0027828,gh20425256,xj0033258,zmj00505562";
//输出  [lt01, wr0068, qhy0027828, xj0033258, zmj00505562, gh20425256]


public class StringSortNumer {
    public static void main(String arg[]){
        String str ="wr0068,lt01,qhy0027828,gh20425256,xj0033258,zmj00505562";
        List<String> strlist = Arrays.asList(str.split(","));
        List<String> sortlist = strlist.stream().sorted((a,b)->Integer.valueOf(subStrChar(a)).compareTo(Integer.valueOf(subStrChar(b)))).collect(Collectors.toList());
//两种排序都正确 
   /*   Collections.sort(strlist, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                int num1=Integer.parseInt(subStrChar(s1));
                int num2=Integer.parseInt(subStrChar(s2));
                return num1-num2;
            }
        });*/
        System.out.println(sortlist);
    }
    // 处理字符串和数字,使用char类型判定字符还是数字,并截取
    public static String subStrChar(String st){
        if (StringUtils.isBlank(st)){
            return null;
        }
        int stopPos=st.length();
        for (int i=0;i<st.length();i++){   遍历 st 的字符
            char c =st.charAt(i);
            if (c>='0' && c<='9'){    // 如果当前字符是数字
                stopPos=i;
                break;
            }
        }
        return st.substring(stopPos,st.length());
    }
}

 

 
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页