如何将String转换为int?

"1234"  →  1234

当前回答

使用不同的字符串输入尝试以下代码:

String a = "10";  
String a = "10ssda";  
String a = null; 
String a = "12102";

if(null != a) {
    try {
        int x = Integer.ParseInt(a.trim()); 
        Integer y = Integer.valueOf(a.trim());
        //  It will throw a NumberFormatException in case of invalid string like ("10ssda" or "123 212") so, put this code into try catch
    } catch(NumberFormatException ex) {
        // ex.getMessage();
    }
}

其他回答

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.parseInt(your_string);将字符串转换为int使用Double.parseDouble(your_string);将字符串转换为double

实例

String str = "8955";
int q = Integer.parseInt(str);
System.out.println("Output>>> " + q); // Output: 8955

String str = "89.55";
double q = Double.parseDouble(str);
System.out.println("Output>>> " + q); // Output: 89.55

公共静态int parseInt(字符串)引发NumberFormatException

可以使用Integer.parseInt()将字符串转换为int。

将字符串“20”转换为原始int:

String n = "20";
int r = Integer.parseInt(n); // Returns a primitive int
System.out.println(r);

输出-20

如果字符串不包含可解析的整数,则将引发NumberFormatException:

String n = "20I"; // Throws NumberFormatException
int r = Integer.parseInt(n);
System.out.println(r);

公共静态Integer valueOf(字符串)引发NumberFormatException

您可以使用Integer.valueOf()。在这种情况下,它将返回一个Integer对象。

String n = "20";
Integer r = Integer.valueOf(n); // Returns a new Integer() object.
System.out.println(r);

输出-20

工具书类https://docs.oracle.com/en/

也可以从删除所有非数字字符开始,然后解析整数:

String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);

但请注意,这只适用于非负数。

手动执行:

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