如何将String转换为int?

"1234"  →  1234

当前回答

使用Integer.parseInt(yourString)。

记住以下几点:

整数.parseInt(“1”);//好啊

整数.parseInt(“-1”);//好啊

整数.parseInt(“+1”);//好啊

整数.parseInt(“1”);//异常(空格)

整数.parseInt(“2147483648”);//异常(整数限制为最大值2147483647)

整数.parseInt(“1.1”);//异常(.或,或任何不允许的)

Integer.parseInt(“”);//异常(不是0或其他)

只有一种类型的异常:NumberFormatException

其他回答

在编程竞赛中,如果您确信数字始终是有效的整数,那么您可以编写自己的方法来解析输入。这将跳过所有与验证相关的代码(因为您不需要任何代码),并且效率会更高一些。

对于有效的正整数:私有静态int parseInt(字符串str){整数i,n=0;对于(i=0;i<str.length();i++){n*=10;n+=str.charAt(i)-48;}返回n;}对于正整数和负整数:私有静态int parseInt(字符串str){int i=0,n=0,符号=1;if(str.charAt(0)==“-”){i=1;符号=-1;}对于(;i<str.length();i++){n*=10;n+=str.charAt(i)-48;}返回符号*n;}如果您希望在这些数字之前或之后有空格,然后确保在进一步处理之前执行str=str.trim()。

手动执行:

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;
}

每当给定的字符串不包含Integer时,您都必须处理这种特殊情况。遗憾的是,标准的Java方法Integer::parseInt和Integer::valueOf抛出一个NumberFormatException来表示这种特殊情况。因此,您必须为流控制使用异常,这通常被认为是错误的编码样式。

在我看来,这种特殊情况应该通过返回一个空的Optional<Integer>来处理。由于Java不提供这种方法,我使用以下包装器:

private Optional<Integer> tryParseInteger(String string) {
    try {
        return Optional.of(Integer.valueOf(string));
    } catch (NumberFormatException e) {
        return Optional.empty();
    }
}

示例用法:

// prints "12"
System.out.println(tryParseInteger("12").map(i -> i.toString()).orElse("invalid"));
// prints "-1"
System.out.println(tryParseInteger("-1").map(i -> i.toString()).orElse("invalid"));
// prints "invalid"
System.out.println(tryParseInteger("ab").map(i -> i.toString()).orElse("invalid"));

虽然这仍然在内部使用流控制的异常,但使用代码变得非常干净。此外,您可以清楚地区分-1被解析为有效值的情况和无法解析无效字符串的情况。

嗯,需要考虑的一个非常重要的点是Integer解析器抛出了Javadoc中所述的NumberFormatException。

int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
      //Will Throw exception!
      //do something! anything to handle the exception.
}

try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
      //No problem this time, but still it is good practice to care about exceptions.
      //Never trust user input :)
      //Do something! Anything to handle the exception.
}

在尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。

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

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

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

Apache NumberUtils API 3.4版