如何将String转换为int?

"1234"  →  1234

当前回答

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

其他回答

这可以起作用,

Integer.parseInt(yourString);

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

嗯,需要考虑的一个非常重要的点是Integer解析器抛出了Javadoc中所述的NumberFormatException。

int foo;
String StringThatCouldBeANumberOrNot = "26263Hello"; //will throw exception
String StringThatCouldBeANumberOrNot2 = "26263"; //will not throw exception
try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot);
} catch (NumberFormatException e) {
      //Will Throw exception!
      //do something! anything to handle the exception.
}

try {
      foo = Integer.parseInt(StringThatCouldBeANumberOrNot2);
} catch (NumberFormatException e) {
      //No problem this time, but still it is good practice to care about exceptions.
      //Never trust user input :)
      //Do something! Anything to handle the exception.
}

在尝试从拆分参数中获取整数值或动态解析某些内容时,处理此异常非常重要。

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

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

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

我们来了

String str = "1234";
int number = Integer.parseInt(str);
print number; // 1234