1

I have a string "AB12TRHW4TR6HH58", i need to split this string and whenever i find a number, i need to perform addition of all. However, if there are consecutive numbers then i need to take it as a whole number. For example, in above string the addition should be done like 12+4+6+58 and so on.

I written below code which adds all numbers individually but cant take a whole number. Could you please help?

public class TestClass {

    public static void main(String[] args) {



        String str = "AB12TRHW4TR6HH58";

        int len = str.length();
        String[] st1 = str.split("");
        int temp1=0;
        for(int i=0;i<=len-1;i++){


                        if(st1[i].matches("[0-9]")){


                        int temp = Integer.parseInt(st1[i]);

                        temp1 = temp+temp1;
                    }

                }

        System.out.println(temp1);

    }

}
2
  • 2
    Possible duplicate of Find all numbers in the String Commented Oct 16, 2018 at 9:16
  • Split your string using letters as separators, you will get an array of decimal numbers. Commented Oct 16, 2018 at 9:17

3 Answers 3

1

Doing what I said in my comment:

    String str = "AB12TRHW4TR6HH58";

    String[] r = str.split("[a-zA-Z]");
    int sum = 0;
    for ( String s : r ) {
        if ( s.length() > 0 ) {
            sum += Integer.parseInt(s);
        }
    }

    System.out.println(sum);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much Stephane. This works perfect and very easy to understand
1

You can split on non-numeric characters and use the resulting array:

String[] st1 = "AB12TRHW4TR6HH58".split("[^0-9]+");
int temp1 = 0;
for (int i = 0; i < st1.length; i++) {
    if (st1[i].isEmpty()) {
        continue;
    }

    temp1 += Integer.parseInt(st1[i]);
}

System.out.println(temp1);

And it can even be simplified further using a stream:

int temp1 = Stream.of(st1)
                .filter(s -> !s.isEmpty())
                .mapToInt(Integer::new)
                .sum();

1 Comment

Works great. Thanks much
1

Instead of splitting around the parts you want to omit, just search what you need: the numbers. Using a Matcher and Stream we can do this like that:

String str = "AB12TRHW4TR6HH58";
Pattern number = Pattern.compile("\\d+");
int sum = number.matcher(str)
        .results()
        .mapToInt(r -> Integer.parseInt(r.group()))
        .sum();
System.out.println(sum); // 80

Or with an additional mapping but using only method references:

int sum = number.matcher(str)
        .results()
        .map(MatchResult::group)
        .mapToInt(Integer::parseInt)
        .sum();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.