如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
实现这一点的两种主要方法是使用Integer类的方法valueOf()和方法parseInt()。
假设给你一个这样的字符串
String numberInString = "999";
然后可以使用
int numberInInteger = Integer.parseInt(numberInString);
或者,您可以使用
int numberInInteger = Integer.valueOf(numberInString);
但这里的问题是,Integer.valueOf()方法在Integer类中有以下实现:
public static Integer valueOf(String var0, int var1) throws NumberFormatException {
return parseInt(var0, var1);
}
如您所见,Integer.valueOf()在内部调用Integer.parseInt()本身。此外,parseInt()返回int,valueOf()则返回Integer
其他回答
我有点惊讶,没有人提到将String作为参数的Integer构造函数。
因此,这里是:
String myString = "1234";
int i1 = new Integer(myString);
Java 8-整数(字符串)。
当然,构造函数将返回类型Integer,并且取消装箱操作将值转换为int。
注1:需要注意的是:此构造函数调用parseInt方法。
public Integer(String var1) throws NumberFormatException {
this.value = parseInt(var1, 10);
}
注2:已弃用:@deprecated(因为=“9”)-JavaDoc。
手动执行:
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;
}
正如我在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;
}
}
我有一个解决方案,但我不知道它有多有效。但它工作得很好,我认为你可以改进它。另一方面,我用JUnit做了几次测试,哪一步正确。我附上了功能和测试:
static public Integer str2Int(String str) {
Integer result = null;
if (null == str || 0 == str.length()) {
return null;
}
try {
result = Integer.parseInt(str);
}
catch (NumberFormatException e) {
String negativeMode = "";
if(str.indexOf('-') != -1)
negativeMode = "-";
str = str.replaceAll("-", "" );
if (str.indexOf('.') != -1) {
str = str.substring(0, str.indexOf('.'));
if (str.length() == 0) {
return (Integer)0;
}
}
String strNum = str.replaceAll("[^\\d]", "" );
if (0 == strNum.length()) {
return null;
}
result = Integer.parseInt(negativeMode + strNum);
}
return result;
}
使用JUnit进行测试:
@Test
public void testStr2Int() {
assertEquals("is numeric", (Integer)(-5), Helper.str2Int("-5"));
assertEquals("is numeric", (Integer)50, Helper.str2Int("50.00"));
assertEquals("is numeric", (Integer)20, Helper.str2Int("$ 20.90"));
assertEquals("is numeric", (Integer)5, Helper.str2Int(" 5.321"));
assertEquals("is numeric", (Integer)1000, Helper.str2Int("1,000.50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int("0.50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int(".50"));
assertEquals("is numeric", (Integer)0, Helper.str2Int("-.10"));
assertEquals("is numeric", (Integer)Integer.MAX_VALUE, Helper.str2Int(""+Integer.MAX_VALUE));
assertEquals("is numeric", (Integer)Integer.MIN_VALUE, Helper.str2Int(""+Integer.MIN_VALUE));
assertEquals("Not
is numeric", null, Helper.str2Int("czv.,xcvsa"));
/**
* Dynamic test
*/
for(Integer num = 0; num < 1000; num++) {
for(int spaces = 1; spaces < 6; spaces++) {
String numStr = String.format("%0"+spaces+"d", num);
Integer numNeg = num * -1;
assertEquals(numStr + ": is numeric", num, Helper.str2Int(numStr));
assertEquals(numNeg + ": is numeric", numNeg, Helper.str2Int("- " + numStr));
}
}
}
使用不同的字符串输入尝试以下代码:
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();
}
}