如何将String转换为int?

"1234"  →  1234

当前回答

我们可以使用Integer包装器类的parseInt(Stringstr)方法将String值转换为整数值。

例如:

String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);

Integer类还提供了valueOf(Stringstr)方法:

String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);

我们还可以使用NumberUtils实用程序类的toInt(StringstrValue)进行转换:

String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);

其他回答

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

除了所有这些答案,我发现了一种新的方法,尽管它在内部使用Integer.parseInt()。

通过使用

import javafx.util.converter.IntegerStringConverter;

new IntegerStringConverter().fromString("1234").intValue()

or

new IntegerStringConverter().fromString("1234")

尽管随着新对象的创建,它的成本有点高。

只需浏览javafx.util.StringConverter<T>类。它有助于将任何包装器类值转换为字符串,反之亦然。

String myString = "1234";
int foo = Integer.parseInt(myString);

如果您查看Java文档,您会注意到“陷阱”是此函数可以引发NumberFormatException,您可以处理该异常:

int foo;
try {
   foo = Integer.parseInt(myString);
}
catch (NumberFormatException e) {
   foo = 0;
}

(此处理方法默认将格式错误的数字设置为0,但如果您愿意,可以执行其他操作。)

或者,您可以使用Guava库中的Ints方法,该方法与Java 8的Optional相结合,为将字符串转换为int提供了一种强大而简洁的方法:

import com.google.common.primitives.Ints;

int foo = Optional.ofNullable(myString)
 .map(Ints::tryParse)
 .orElse(0)

实现这一点的两种主要方法是使用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

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

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

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

Apache NumberUtils API 3.4版