如何将String转换为int?

"1234"  →  1234

当前回答

对于普通字符串,可以使用:

int number = Integer.parseInt("1234");

对于字符串生成器和字符串缓冲区,可以使用:

Integer.parseInt(myBuilderOrBuffer.toString());

其他回答

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

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

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

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

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

Apache NumberUtils API 3.4版

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

确保字符串中没有非数字数据。

对于Java 11,有几种方法可以将int转换为String类型:

1) 整数.parseInt()

String str = "1234";
int result = Integer.parseInt(str);

2) Integer.valueOf()

String str = "1234";
int result = Integer.valueOf(str).intValue();

3) 整数构造函数

  String str = "1234";
  Integer result = new Integer(str);

4) 整数代码

String str = "1234";
int result = Integer.decode(str);

将字符串转换为int比仅转换数字更复杂。您已经考虑了以下问题:

字符串是否只包含数字0-9?字符串之前或之后的-/+怎么了?这是可能的吗(指会计数字)?MAX_-/MIN_INFINITY怎么了?如果字符串为99999999999999999999,会发生什么?机器可以将此字符串视为int吗?