在字符串中提取整数部分
-
19-09-2019 - |
题
什么是提取字符串整数部分的最佳方法
Hello123
您如何获得123部分。您可以使用Java的扫描仪进行侵略,有更好的方法吗?
解决方案
您为什么不只是使用正则表达式来匹配所需的字符串部分?
[0-9]
这就是您所需要的,再加上它需要的任何周围炭。
看着 http://www.regular-expressions.info/tutorial.html 了解正则表达方式的工作原理。
编辑:我想说的是,如果确实如此,那么如果确实,其他提交者发布的代码可能有点过分...但是我仍然建议学习Regex的Regex,因为它们非常强大,并且比我想承认的要派上用场的(在给他们射击之前等待了几年之后)。
其他提示
如前所述,尝试使用正则表达式。这应该有所帮助:
String value = "Hello123";
String intValue = value.replaceAll("[^0-9]", ""); // returns 123
然后,您只需将其从那里转换为INT(或整数)即可。
我相信您可以做类似的事情:
Scanner in = new Scanner("Hello123").useDelimiter("[^0-9]+");
int integer = in.nextInt();
编辑:Carlos添加了二手仪的建议
假设您想要一个尾巴,这将有效:
import java.util.regex.*;
public class Example {
public static void main(String[] args) {
Pattern regex = Pattern.compile("\\D*(\\d*)");
String input = "Hello123";
Matcher matcher = regex.matcher(input);
if (matcher.matches() && matcher.groupCount() == 1) {
String digitStr = matcher.group(1);
Integer digit = Integer.parseInt(digitStr);
System.out.println(digit);
}
System.out.println("done.");
}
}
我一直认为Michael的正则是最简单的解决方案,但是第二个想法仅需“ d+”,如果您使用matcher.find()而不是matcher.matches():
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class Example {
public static void main(String[] args) {
String input = "Hello123";
int output = extractInt(input);
System.out.println("input [" + input + "], output [" + output + "]");
}
//
// Parses first group of consecutive digits found into an int.
//
public static int extractInt(String str) {
Matcher matcher = Pattern.compile("\\d+").matcher(str);
if (!matcher.find())
throw new NumberFormatException("For input string [" + str + "]");
return Integer.parseInt(matcher.group());
}
}
尽管我知道这是一个6岁的问题,但是我正在为那些想避免现在学习正则态度的人(您应该顺便说一句)。这种方法还给出了数字之间的数字(例如HP123KT567 将返回123567)
Scanner scan = new Scanner(new InputStreamReader(System.in));
System.out.print("Enter alphaNumeric: ");
String x = scan.next();
String numStr = "";
int num;
for (int i = 0; i < x.length(); i++) {
char charCheck = x.charAt(i);
if(Character.isDigit(charCheck)) {
numStr += charCheck;
}
}
num = Integer.parseInt(numStr);
System.out.println("The extracted number is: " + num);
String[] parts = s.split("\\D+"); //s is string containing integers
int[] a;
a = new int[parts.length];
for(int i=0; i<parts.length; i++){
a[i]= Integer.parseInt(parts[i]);
System.out.println(a[i]);
}
不隶属于 StackOverflow