正整数的字符串转数字(java)

正整数的字符串转数字(java)

由部分BigDecimal源码改编而来

(public BigDecimal(char[] in, int offset, int len, MathContext mc){})

public static void main(String[] args) {
        //正整数的字符串转数字
        String num1="001234";
        System.out.println("排除前置0: "+strToNum(num1));
        //排除前置0: 1234
        String num2="1234";
        System.out.println("正常转换: "+strToNum(num2));
        //正常转换: 1234
        String num3="1230kk4";
        System.out.println("排除非数字字符: "+strToNum(num3));
        //排除非数字字符: 12304
        String num4="+12304";
        System.out.println("排除前置+: "+strToNum(num4));
        //排除前置+: 12304
    }

    private static int strToNum(String str) {
        char[] chars = str.toCharArray();
        int off = 0;
        int val = 0;
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == '0' && off == 0) {
                continue;
            }
            int suf = c - '0';
            if (suf >= 0 && suf <= 9) {
                val = val * 10 + suf;
                off++;
            }
        }
        return val;
    }

 

posted @ 2022-04-02 18:51  进击的小蔡鸟  阅读(74)  评论(0编辑  收藏  举报