字符串转整数

将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

public static int StrToInt(String str) {
        if (null == str || str.length() == 0){
            return 0;
        }
        boolean flag = true;
        int i = 0;
        int num = 0;
        if (str.charAt(0) == '+' || str.charAt(0) == '-'){
            flag = str.charAt(0) == '+';
            i = 1;
        }
        while (i < str.length()){
            if (str.charAt(i) < '0' || str.charAt(i) > '9'){
                return 0;
            }
            num = num * 10 + str.charAt(i) - '0';
            i++;
        }
        return flag ? num : -num;
    }
原文地址:https://www.cnblogs.com/earthhouge/p/11065909.html