如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
手动执行:
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;
}
其他回答
使用Integer.parseInt(yourString)。
记住以下几点:
整数.parseInt(“1”);//好啊
整数.parseInt(“-1”);//好啊
整数.parseInt(“+1”);//好啊
整数.parseInt(“1”);//异常(空格)
整数.parseInt(“2147483648”);//异常(整数限制为最大值2147483647)
整数.parseInt(“1.1”);//异常(.或,或任何不允许的)
Integer.parseInt(“”);//异常(不是0或其他)
只有一种类型的异常:NumberFormatException
将字符串转换为int比仅转换数字更复杂。您已经考虑了以下问题:
字符串是否只包含数字0-9?字符串之前或之后的-/+怎么了?这是可能的吗(指会计数字)?MAX_-/MIN_INFINITY怎么了?如果字符串为99999999999999999999,会发生什么?机器可以将此字符串视为int吗?
正如我在GitHub上写的:
public class StringToInteger {
public static void main(String[] args) {
assert parseInt("123") == Integer.parseInt("123");
assert parseInt("-123") == Integer.parseInt("-123");
assert parseInt("0123") == Integer.parseInt("0123");
assert parseInt("+123") == Integer.parseInt("+123");
}
/**
* Parse a string to integer
*
* @param s the string
* @return the integer value represented by the argument in decimal.
* @throws NumberFormatException if the {@code string} does not contain a parsable integer.
*/
public static int parseInt(String s) {
if (s == null) {
throw new NumberFormatException("null");
}
boolean isNegative = s.charAt(0) == '-';
boolean isPositive = s.charAt(0) == '+';
int number = 0;
for (int i = isNegative ? 1 : isPositive ? 1 : 0, length = s.length(); i < length; ++i) {
if (!Character.isDigit(s.charAt(i))) {
throw new NumberFormatException("s=" + s);
}
number = number * 10 + s.charAt(i) - '0';
}
return isNegative ? -number : number;
}
}
例如,这里有两种方法:
Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);
这些方法略有不同:
valueOf返回java.lang.Integer的新实例或缓存实例parseInt返回基元int。
所有情况都是一样的:Short.valueOf/parseShort、Long.valueOf/parseLong等。
Google Guava有tryParse(String),如果无法解析字符串,则返回null,例如:
Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
...
}