我有一个可变长度的字符串,在字符串的末尾是一些数字.什么是最好/最有效的方法,解析字符串并从最终获得数字作为整数?
字符串和末尾的数字可以是任意长度.例如:
abcd123 --> 123 abc12345 --> 12345 ab4cd1 --> 1
Von*_*onC 19
沿线的东西:
final static Pattern lastIntPattern = Pattern.compile("[^0-9]+([0-9]+)$");
String input = "...";
Matcher matcher = lastIntPattern.matcher(input);
if (matcher.find()) {
String someNumberStr = matcher.group(1);
int lastNumberInt = Integer.parseInt(someNumberStr);
}
Run Code Online (Sandbox Code Playgroud)
能做到这.
这不是"最有效"的方式,但除非你有一个围绕这个代码的关键瓶颈(如:从数百万字符串中提取int),这应该就足够了.
这里提供的其他解决方案都很好,所以我将提供这个只是有点不同:
public static BigInteger lastBigInteger(String s) {
int i = s.length();
while (i > 0 && Character.isDigit(s.charAt(i - 1))) {
i--;
}
return new BigInteger(s.substring(i));
}
Run Code Online (Sandbox Code Playgroud)
Character.isDigit(char)
BigInteger,因此它可以在真正长字符串的末尾处理非常大的数字.
Integer.parseInt或Long.parseLong是否满足| 归档时间: |
|
| 查看次数: |
11039 次 |
| 最近记录: |