欢迎来到Java学习网!
设为首页 | 加入收藏
当前位置: 首页 > Java语言 > Java教程 >
Java解析以任何字符分隔的数字字符串

Java代码:

    public static void main(String[] args) throws Exception {
        String numStr = "1fda2321fdf,1231 214 \n 345n234 23423saf23";
        List<Integer> list = parseNum2List(numStr);
        System.out.println(list);
    }

    private static List<Integer> parseNum2List(String numStr) {
        List<Integer> list = new ArrayList<Integer>();
        StringBuilder sb = null;
        int len = numStr.length();
        for (int i = 0;i < len;i++) {
            char ch = numStr.charAt(i);
            if (Character.isDigit(ch)) {
                if(null == sb){
                    sb = new StringBuilder();
                }
                sb.append(ch);
            } else {
                if (null != sb) {
                    list.add(StringUtil.toInt(sb.toString()));
                    sb = null;
                }
            }
        }
        // Add the last num.
        if (null != sb) {
            list.add(StringUtil.toInt(sb.toString()));
        }
        return list;
    }

Java代码输出:[1, 2321, 1231, 214, 345, 234, 23423, 23]
    相关教程
    推荐内容