Java 字符串(String)转成数字int的几种常用方法
Java 字符串(String)转成数字int的几种常用方法
1、使用Integer.parseInt()和Integer.parseUnsignedInt实现
String myString = "1314"; int foo = Integer.parseInt(myString);
或者
String mystr = mystr.replaceAll("[^\\d]", ""); int number = Integer.parseInt(mystr);
或者
int foo; try { foo = Integer.parseInt(myString); } catch (NumberFormatException e) { foo = 0; }
或者
import com.google.common.primitives.Ints; int foo = Optional.ofNullable(myString) .map(Ints::tryParse) .orElse(0)
或者
int result = Integer.parseUnsignedInt(number);
2、使用Integer.valueOf()实现
String strValue = "520"; Integer intValue = Integer.valueOf(strValue);
3、使用NumberUtils.toInt()实现
String strValue = "1520"; Integer intValue = NumberUtils.toInt(strValue); NumberUtils.toInt("3244", 1) = 3244 NumberUtils.toInt("", 1) = 1 NumberUtils.toInt(null, 5) = 5 NumberUtils.toInt("Hi", 6) = 6 NumberUtils.toInt(" 32 ", 1) = 1 // 空格字符在数字是允许,所以是默认值
4、使用自定义方法实现转换失败的默认值
private Optional<Integer> tryParseInteger(String string) { try { return Optional.of(Integer.valueOf(string)); } catch (NumberFormatException e) { return Optional.empty(); } }
或者
public static int parseIntOrDefault(String value, int defaultValue) { int result = defaultValue; try { result = Integer.parseInt(value); } catch (Exception e) { } return result; } public static int parseIntOrDefault(String value, int beginIndex, int defaultValue) { int result = defaultValue; try { String stringValue = value.substring(beginIndex); result = Integer.parseInt(stringValue); } catch (Exception e) { } return result; } public static int parseIntOrDefault(String value, int beginIndex, int endIndex, int defaultValue) { int result = defaultValue; try { String stringValue = value.substring(beginIndex, endIndex); result = Integer.parseInt(stringValue); } catch (Exception e) { } return result; } //测试
public static void main(String[] args) { System.out.println(parseIntOrDefault("123", 0)); // 123 System.out.println(parseIntOrDefault("aaa", 0)); // 0 System.out.println(parseIntOrDefault("aaa456", 3, 0)); // 456 System.out.println(parseIntOrDefault("aaa789bbb", 3, 6, 0)); // 789 }
4、使用Integer.decode实现
Integer.decode("12"); // 12 - Integer Integer.decode("#12"); // 18 - Integer Integer.decode("0x12"); // 18 - Integer Integer.decode("0X12"); // 18 - Integer
拆箱:int val = Integer.decode("12");
intValue():Integer.decode("12").intValue();
5、使用NumberUtils.createInteger实现
Integer result = NumberUtils.createInteger(number);
6、使用Ints.tryParse实现
int result = Ints.tryParse(number);
注意:string
转int
不能直接(int)强制转换,当float/double
类型转int可以强制转换。