0

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 )

4
  • 5
    javasript !===== java Commented Dec 7, 2016 at 9:29
  • 4
    stackoverflow.com/questions/12216065/… Commented Dec 7, 2016 at 9:34
  • @Guy I would recommend this answer: stackoverflow.com/a/12216123/982149 over the accepted answer in the question you linked. Commented Dec 7, 2016 at 9:36
  • @Fildor So do I, but its up to the OP. Commented Dec 7, 2016 at 9:38

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It worked. @Patrick
glad to hear that @pb_! Please don't forget to mark an Accepted answer.
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());
    }

1 Comment

This too worked @Anh Pham
1

With Java 8:

String str = "ab34yuj789km2";
int sum = Arrays.stream(str.split("\\D+"))
    .filter(s -> !s.isEmpty())
    .mapToInt(s -> Integer.parseInt(s))
    .sum();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.