如何将String转换为int?

"1234"  →  1234

当前回答

手动执行:

public static int strToInt(String str){
    int i = 0;
    int num = 0;
    boolean isNeg = false;

    // Check for negative sign; if it's there, set the isNeg flag
    if (str.charAt(0) == '-') {
        isNeg = true;
        i = 1;
    }

    // Process each character of the string;
    while( i < str.length()) {
        num *= 10;
        num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).
    }

    if (isNeg)
        num = -num;
    return num;
}

其他回答

正如我在GitHub上写的:

public class StringToInteger {
    public static void main(String[] args) {
        assert parseInt("123") == Integer.parseInt("123");
        assert parseInt("-123") == Integer.parseInt("-123");
        assert parseInt("0123") == Integer.parseInt("0123");
        assert parseInt("+123") == Integer.parseInt("+123");
    }

    /**
     * Parse a string to integer
     *
     * @param s the string
     * @return the integer value represented by the argument in decimal.
     * @throws NumberFormatException if the {@code string} does not contain a parsable integer.
     */
    public static int parseInt(String s) {
        if (s == null) {
            throw new NumberFormatException("null");
        }
        boolean isNegative = s.charAt(0) == '-';
        boolean isPositive = s.charAt(0) == '+';
        int number = 0;
        for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
            if (!Character.isDigit(s.charAt(i))) {
                throw new NumberFormatException("s=" + s);
            }
            number = number * 10 + s.charAt(i) - '0';
        }
        return isNegative ? -number : number;
    }
}

公共静态int parseInt(字符串)引发NumberFormatException

可以使用Integer.parseInt()将字符串转换为int。

将字符串“20”转换为原始int:

String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);

输出-20

如果字符串不包含可解析的整数,则将引发NumberFormatException:

String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

公共静态Integer valueOf(字符串)引发NumberFormatException

您可以使用Integer.valueOf()。在这种情况下,它将返回一个Integer对象。

String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);

输出-20

工具书类https://docs.oracle.com/en/

另一种解决方案是使用Apache Commons的NumberUtils:

int num = NumberUtils.toInt("1234");

Apache实用程序很好,因为如果字符串是无效的数字格式,则始终返回0。因此,节省了try-catch块。

Apache NumberUtils API 3.4版

如上所述,Apache Commons的NumberUtils可以做到这一点。如果无法将字符串转换为int,则返回0。

您还可以定义自己的默认值:

NumberUtils.toInt(String str, int defaultValue)

例子:

NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1)     = 1
NumberUtils.toInt(null, 5)   = 5
NumberUtils.toInt("Hi", 6)   = 6
NumberUtils.toInt(" 32 ", 1) = 1 // Space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty("  32 ", 1)) = 32;

您可以使用new Scanner(“1244”).netInt()。或者询问是否存在int:new Scanner