如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
除了所有这些答案,我发现了一种新的方法,尽管它在内部使用Integer.parseInt()。
通过使用
import javafx.util.converter.IntegerStringConverter;
new IntegerStringConverter().fromString("1234").intValue()
or
new IntegerStringConverter().fromString("1234")
尽管随着新对象的创建,它的成本有点高。
只需浏览javafx.util.StringConverter<T>类。它有助于将任何包装器类值转换为字符串,反之亦然。
其他回答
如上所述,Apache Commons的NumberUtils可以做到这一点。如果无法将字符串转换为int,则返回0。
您还可以定义自己的默认值:
NumberUtils.toInt(String str, int defaultValue)
例子:
NumberUtils.toInt("3244", 1) = 3244
NumberUtils.toInt("", 1) = 1
NumberUtils.toInt(null, 5) = 5
NumberUtils.toInt("Hi", 6) = 6
NumberUtils.toInt(" 32 ", 1) = 1 // Space in numbers are not allowed
NumberUtils.toInt(StringUtils.trimToEmpty(" 32 ", 1)) = 32;
对于普通字符串,可以使用:
int number = Integer.parseInt("1234");
对于字符串生成器和字符串缓冲区,可以使用:
Integer.parseInt(myBuilderOrBuffer.toString());
对于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
}
我们可以使用Integer包装器类的parseInt(Stringstr)方法将String值转换为整数值。
例如:
String strValue = "12345";
Integer intValue = Integer.parseInt(strVal);
Integer类还提供了valueOf(Stringstr)方法:
String strValue = "12345";
Integer intValue = Integer.valueOf(strValue);
我们还可以使用NumberUtils实用程序类的toInt(StringstrValue)进行转换:
String strValue = "12345";
Integer intValue = NumberUtils.toInt(strValue);
使用Integer.parseInt(yourString)。
记住以下几点:
整数.parseInt(“1”);//好啊
整数.parseInt(“-1”);//好啊
整数.parseInt(“+1”);//好啊
整数.parseInt(“1”);//异常(空格)
整数.parseInt(“2147483648”);//异常(整数限制为最大值2147483647)
整数.parseInt(“1.1”);//异常(.或,或任何不允许的)
Integer.parseInt(“”);//异常(不是0或其他)
只有一种类型的异常:NumberFormatException