问题
I want to extract the integers from string and add them.
Ex :
String s="ab34yuj789km2";
I should get the output of integers from it as 825 ( i.e., 34 + 789 + 2 = 825 )
回答1:
Here's one way, by using String.split:
public static void main(String[] args) {
String s="ab34yuj789km2";
int total = 0;
for(String numString : s.split("[^0-9]+")) {
if(!numString.isEmpty()) {
total += Integer.parseInt(numString);
}
}
// Print the result
System.out.println("Total = " + total);
}
Note the pattern "[^0-9]+"
is a regular expression. It matches one or more characters that are not decimal numbers. There is also a pattern \d
for decimal numbers.
回答2:
You can extract the number from string by using regex.
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("ab34yuj789km2");
Integer sum = 0;
while(matcher.find()) {
sum += Integer.parseInt(matcher.group());
}
回答3:
With Java 8:
String str = "ab34yuj789km2";
int sum = Arrays.stream(str.split("\\D+"))
.filter(s -> !s.isEmpty())
.mapToInt(s -> Integer.parseInt(s))
.sum();
来源:https://stackoverflow.com/questions/41013747/extract-integers-from-string-and-add-them-in-java