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 )
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.
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());
}
javasript!=====java