如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
有多种方法可以将字符串int值转换为Integer数据类型值。您需要处理字符串值问题的NumberFormatException。
整数.分析Intfoo=整数.parseInt(myString);整数值foo=Integer.valueOf(myString);使用Java 8可选APIfoo=可选.Nullable(myString).map(整数::parseInt).get();
其他回答
方法:
整数.parseInt整数.parseInt(s,基数)Integer.parseInt(s,beginIndex,endIndex,基数)整数.parseUnsignedInt整数.parseUnsignedInt(s,基数)Integer.parseUnsignedInt(s,beginIndex,endIndex,基数)整数.valueOf整数.valueOf(s,基数)整数.解码数字Utils.toInt(s)NumberUtils.toInt(s,默认值)
Integer.valueOf生成一个Integer对象,而所有其他方法生成一个基元int。
最后两个方法来自commons-lang3和一篇关于转换的大文章。
int foo = Integer.parseInt("1234");
确保字符串中没有非数字数据。
对于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);
手动执行:
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;
}
使用不同的字符串输入尝试以下代码:
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();
}
}