如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
Google Guava有tryParse(String),如果无法解析字符串,则返回null,例如:
Integer fooInt = Ints.tryParse(fooString);
if (fooInt != null) {
...
}
其他回答
方法:
整数.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和一篇关于转换的大文章。
您可以有自己的实现,例如:
public class NumericStringToInt {
public static void main(String[] args) {
String str = "123459";
int num = stringToNumber(str);
System.out.println("Number of " + str + " is: " + num);
}
private static int stringToNumber(String str) {
int num = 0;
int i = 0;
while (i < str.length()) {
char ch = str.charAt(i);
if (ch < 48 || ch > 57)
throw new NumberFormatException("" + ch);
num = num * 10 + Character.getNumericValue(ch);
i++;
}
return num;
}
}
我有一个解决方案,但我不知道它有多有效。但它工作得很好,我认为你可以改进它。另一方面,我用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));
}
}
}
对于Android开发者来说,以下是Kotlin的各种解决方案:
// Throws exception if number has bad form
val result1 = "1234".toInt()
// Will be null if number has bad form
val result2 = "1234"
.runCatching(String::toInt)
.getOrNull()
// Will be the given default if number has bad form
val result3 = "1234"
.runCatching(String::toInt)
.getOrDefault(0)
// Will be return of the else block if number has bad form
val result4 = "1234"
.runCatching(String::toInt)
.getOrElse {
// some code
// return an Int
}
使用不同的字符串输入尝试以下代码:
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();
}
}