如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
Google Guava有tryParse(String),如果无法解析字符串,则返回null,例如:
Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
...
}
其他回答
手动执行:
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;
}
您也可以使用此代码,但要注意一些事项。
选项#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;}
使用字符串常量进行比较或任何类型的计算总是一个好主意,因为常量永远不会返回空值。
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)
另一种解决方案是使用Apache Commons的NumberUtils:
int num = NumberUtils.toInt("1234");
Apache实用程序很好,因为如果字符串是无效的数字格式,则始终返回0。因此,节省了try-catch块。
Apache NumberUtils API 3.4版
如上所述,Apache Commons的NumberUtils可以做到这一点。如果无法将字符串转换为int,则返回0。
您还可以定义自己的默认值:
NumberUtils.toInt(String str, int defaultValue)
例子:
NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1) = 1
NumberUtils.toInt(null, 5) = 5
NumberUtils.toInt("Hi", 6) = 6
NumberUtils.toInt(" 32 ", 1) = 1 // Space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty(" 32 ", 1)) = 32;