如何将String转换为int?

"1234"  →  1234

当前回答

正如我在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;
    }
}

其他回答

如果需要原语,请使用parseInt,否则使用Integer.valueOf()

对于Android开发者来说,以下是Kotlin的各种解决方案:

// Throws exception if number has bad form
val result1 = "1234".toInt()
// Will be null if number has bad form
val result2 = "1234"
    .runCatching(String::toInt)
    .getOrNull()
// Will be the given default if number has bad form
val result3 = "1234"
    .runCatching(String::toInt)
    .getOrDefault(0)
// Will be return of the else block if number has bad form
val result4 = "1234"
    .runCatching(String::toInt)
    .getOrElse {
        // some code
        // return an Int
    }

也可以从删除所有非数字字符开始,然后解析整数:

String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);

但请注意,这只适用于非负数。

公共静态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/

您可以有自己的实现,例如:

public class NumericStringToInt {

    public static void main(String[] args) {
        String str = "123459";

        int num = stringToNumber(str);
        System.out.println("Number of " + str + " is: " + num);
    }

    private static int stringToNumber(String str) {

        int num = 0;
        int i = 0;
        while (i < str.length()) {
            char ch = str.charAt(i);
            if (ch < 48 || ch > 57)
                throw new NumberFormatException("" + ch);
            num = num * 10 + Character.getNumericValue(ch);
            i++;
        }
        return num;
    }
}