如何将String转换为int?

"1234"  →  1234

当前回答

您也可以使用此代码,但要注意一些事项。

选项#1:显式处理异常,例如,显示消息对话框,然后停止当前工作流的执行。例如:尝试{字符串字符串值=“1234”;//从字符串到整数int integerValue=Integer.valueOf(stringValue);//或int整数值=整数.ParseInt(字符串值);//现在从整数返回字符串stringValue=String.valueOf(整数值);}catch(NumberFormatException ex){//JOptionPane.showMessageDialog(帧,“无效输入字符串!”);System.out.println(“输入字符串无效!”);回来}选项#2:如果发生异常,执行流可以继续,则重置受影响的变量。例如,在catch块中进行了一些修改catch(NumberFormatException ex){整数值=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;
}

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

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

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

Apache NumberUtils API 3.4版

这可以起作用,

Integer.parseInt(yourString);

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

将String转换为Int的一些方法如下:

可以使用Integer.parseInt():字符串测试=“4568”;int new=Integer.parseInt(测试);也可以使用Integer.valueOf():字符串测试=“4568”;int new=Integer.valueOf(测试);