如何将String转换为int?

"1234"  →  1234

当前回答

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

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

其他回答

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

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

如果需要原语,请使用parseInt,否则使用Integer.valueOf()

// As per your question "1234"  →  1234   
//using Integer.parseInt() method
public class StringToIntExample1{
 public static void main(String args[]){
 //Declaring String variable
  String s="1234";
 //Converting String into int using Integer.parseInt()
  int i=Integer.parseInt(s);
 //Printing value of i
  System.out.println(i);  
 }
} 

对于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);