如何将String转换为int?
"1234" → 1234
如何将String转换为int?
"1234" → 1234
当前回答
每当给定的字符串不包含Integer时,您都必须处理这种特殊情况。遗憾的是,标准的Java方法Integer::parseInt和Integer::valueOf抛出一个NumberFormatException来表示这种特殊情况。因此,您必须为流控制使用异常,这通常被认为是错误的编码样式。
在我看来,这种特殊情况应该通过返回一个空的Optional<Integer>来处理。由于Java不提供这种方法,我使用以下包装器:
private Optional<Integer> tryParseInteger(String string) {
try {
return Optional.of(Integer.valueOf(string));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
示例用法:
// prints "12"
System.out.println(tryParseInteger("12").map(i -> i.toString()).orElse("invalid"));
// prints "-1"
System.out.println(tryParseInteger("-1").map(i -> i.toString()).orElse("invalid"));
// prints "invalid"
System.out.println(tryParseInteger("ab").map(i -> i.toString()).orElse("invalid"));
虽然这仍然在内部使用流控制的异常,但使用代码变得非常干净。此外,您可以清楚地区分-1被解析为有效值的情况和无法解析无效字符串的情况。
其他回答
如上所述,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;
也可以从删除所有非数字字符开始,然后解析整数:
String mystr = mystr.replaceAll("[^\\d]", "");
int number = Integer.parseInt(mystr);
但请注意,这只适用于非负数。
整数代码
您还可以使用公共静态整数解码(Stringnm)抛出NumberFormatException。
它也适用于底座8和16:
// base 10
Integer.parseInt("12"); // 12 - int
Integer.valueOf("12"); // 12 - Integer
Integer.decode("12"); // 12 - Integer
// base 8
// 10 (0,1,...,7,10,11,12)
Integer.parseInt("12", 8); // 10 - int
Integer.valueOf("12", 8); // 10 - Integer
Integer.decode("012"); // 10 - Integer
// base 16
// 18 (0,1,...,F,10,11,12)
Integer.parseInt("12",16); // 18 - int
Integer.valueOf("12",16); // 18 - Integer
Integer.decode("#12"); // 18 - Integer
Integer.decode("0x12"); // 18 - Integer
Integer.decode("0X12"); // 18 - Integer
// base 2
Integer.parseInt("11",2); // 3 - int
Integer.valueOf("11",2); // 3 - Integer
如果要获取int而不是Integer,可以使用:
取消装箱:int val=Integer.decode(“12”);intValue():Integer.decode(“12”).intValue();
您可以有自己的实现,例如:
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;
}
}
import java.util.*;
public class strToint {
public static void main(String[] args) {
String str = "123";
byte barr[] = str.getBytes();
System.out.println(Arrays.toString(barr));
int result = 0;
for(int i = 0; i < barr.length; i++) {
//System.out.print(barr[i]+" ");
int ii = barr[i];
char a = (char) ii;
int no = Character.getNumericValue(a);
result = result * 10 + no;
System.out.println(result);
}
System.out.println("result:"+result);
}
}