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);

    }

}
Nit QA
  • 37
  • 2
  • 3
  • 8
  • 2
    Possible duplicate of [Find all numbers in the String](https://stackoverflow.com/questions/13440506/find-all-numbers-in-the-string) –  Oct 16 '18 at 09:16
  • Split your string using letters as separators, you will get an array of decimal numbers. – StephaneM Oct 16 '18 at 09:17

3 Answers3

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();
ernest_k
  • 44,416
  • 5
  • 53
  • 99
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);
StephaneM
  • 4,779
  • 1
  • 16
  • 33
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();
LuCio
  • 5,055
  • 2
  • 18
  • 34