如何将String转换为int?

"1234"  →  1234

当前回答

实现这一点的两种主要方法是使用Integer类的方法valueOf()和方法parseInt()。

假设给你一个这样的字符串

String numberInString = "999";

然后可以使用

int numberInInteger = Integer.parseInt(numberInString);

或者,您可以使用

int numberInInteger = Integer.valueOf(numberInString);

但这里的问题是,Integer.valueOf()方法在Integer类中有以下实现:

public static Integer valueOf(String var0, int var1) throws NumberFormatException {
    return parseInt(var0, var1);
}

如您所见,Integer.valueOf()在内部调用Integer.parseInt()本身。此外,parseInt()返回int,valueOf()则返回Integer

其他回答

我们来了

String str = "1234";
int number = Integer.parseInt(str);
print number; // 1234

我有点惊讶,没有人提到将String作为参数的Integer构造函数。

因此,这里是:

String myString = "1234";
int i1 = new Integer(myString);

Java 8-整数(字符串)。

当然,构造函数将返回类型Integer,并且取消装箱操作将值转换为int。


注1:需要注意的是:此构造函数调用parseInt方法。

public Integer(String var1) throws NumberFormatException {
    this.value = parseInt(var1, 10);
}

注2:已弃用:@deprecated(因为=“9”)-JavaDoc。

手动执行:

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解析器抛出了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.
}

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

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