如何将String转换为int?

"1234"  →  1234

当前回答

一个方法是parseInt(String)。它返回一个基元int:

String number = "10";
int result = Integer.parseInt(number);
System.out.println(result);

第二个方法是valueOf(String),它返回一个新的Integer()对象:

String number = "10";
Integer result = Integer.valueOf(number);
System.out.println(result);

其他回答

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)

手动执行:

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.parseInt(yourString)。

记住以下几点:

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

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

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

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

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

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

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

只有一种类型的异常:NumberFormatException

整数代码

您还可以使用公共静态整数解码(Stringnm)抛出NumberFormatException。

它也适用于底座8和16:

// base 10
Integer.parseInt("12");     // 12 - int
Integer.valueOf("12");      // 12 - Integer
Integer.decode("12");       // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8);  // 10 - int
Integer.valueOf("12", 8);   // 10 - Integer
Integer.decode("012");      // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16);  // 18 - int
Integer.valueOf("12",16);   // 18 - Integer
Integer.decode("#12");      // 18 - Integer
Integer.decode("0x12");     // 18 - Integer
Integer.decode("0X12");     // 18 - Integer
// base 2
Integer.parseInt("11",2);   // 3 - int
Integer.valueOf("11",2);    // 3 - Integer

如果要获取int而不是Integer,可以使用:

取消装箱:int val=Integer.decode(“12”);intValue():Integer.decode(“12”).intValue();

对于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
    }