如何将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();
其他回答
我有点惊讶,没有人提到将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。
我有一个解决方案,但我不知道它有多有效。但它工作得很好,我认为你可以改进它。另一方面,我用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转换为Int的一些方法如下:
可以使用Integer.parseInt():字符串测试=“4568”;int new=Integer.parseInt(测试);也可以使用Integer.valueOf():字符串测试=“4568”;int new=Integer.valueOf(测试);
// 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);
}
}
使用此方法可以避免错误。
String myString = "1234";
int myInt;
if(Integer.parseInt(myString), out myInt){};