考虑到现有的答案,我已经复制粘贴并增强了源代码Integer.parseInt
来完成这项工作,而我的解决方案
- 不使用可能会很慢的try-catch(与Lang 3 NumberUtils不同),
- 不使用不能捕获太大数字的正则表达式,
- 避免拳击(与番石榴不同
Ints.tryParse()
),
- 不需要任何的分配(不像
int[]
,Box
,OptionalInt
),
- 接受其中的任何
CharSequence
或一部分,而不是整个String
,
- 可以使用
Integer.parseInt
可以[2,36]的任何基数
- 不依赖于任何库。
唯一的缺点是toIntOfDefault("-1", -1)
和之间没有区别toIntOrDefault("oops", -1)
。
public static int toIntOrDefault(CharSequence s, int def) {
return toIntOrDefault0(s, 0, s.length(), 10, def);
}
public static int toIntOrDefault(CharSequence s, int def, int radix) {
radixCheck(radix);
return toIntOrDefault0(s, 0, s.length(), radix, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int def) {
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, 10, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int radix, int def) {
radixCheck(radix);
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, radix, def);
}
private static int toIntOrDefault0(CharSequence s, int start, int endExclusive, int radix, int def) {
if (start == endExclusive) return def; // empty
boolean negative = false;
int limit = -Integer.MAX_VALUE;
char firstChar = s.charAt(start);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+') {
return def;
}
start++;
// Cannot have lone "+" or "-"
if (start == endExclusive) return def;
}
int multmin = limit / radix;
int result = 0;
while (start < endExclusive) {
// Accumulating negatively avoids surprises near MAX_VALUE
int digit = Character.digit(s.charAt(start++), radix);
if (digit < 0 || result < multmin) return def;
result *= radix;
if (result < limit + digit) return def;
result -= digit;
}
return negative ? result : -result;
}
private static void radixCheck(int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
throw new NumberFormatException(
"radix=" + radix + " ∉ [" + Character.MIN_RADIX + "," + Character.MAX_RADIX + "]");
}
private static void boundsCheck(int start, int endExclusive, int len) {
if (start < 0 || start > len || start > endExclusive)
throw new IndexOutOfBoundsException("start=" + start + " ∉ [0, min(" + len + ", " + endExclusive + ")]");
if (endExclusive > len)
throw new IndexOutOfBoundsException("endExclusive=" + endExclusive + " > s.length=" + len);
}