简体   繁体   中英

Finding the sum of NUMBERS in a string?

I have to find the sum of numbers in a string which contains "az", "0-9" and "-", if there is "-" before the number I count this number as negative. For example I have this text:

asd-12sdf45-56asdf100 , the sum of numbers -12,45,-56 and 100 is 77 .

I managed to replace all the letters and it came out -12 45-56 100 , and I am stuck here. I tried splitting into array and then parseInt , I tried some things with loops, but dead end... Any help?

It might not be entire code; if you give just a hint, I can probably figure the rest out myself.

Here is the code I've wrote so far.

String text = "asd-12sdf45-56asdf100";
String numbers = text.replaceAll("[a-zA-Z]+", " ");
String[] num = numbers.trim().split("[ ]");

int sum = 0;
for (int index = 0; index < num.length; index++) {
    int n = Integer.parseInt(num[index]);
    sum += n;
}
System.out.println(sum);

PS: I am still in the beginning of my IT education, so keep it as simple as possible :D Thanks in advance!

String s = "-12 45-56 100";
int sum = Stream.of(s.replaceAll("-", " -").split(" ")).filter(e -> !"".equals(e)).mapToInt(Integer::parseInt).sum();

This sounds a lot like a homework question for you to learn regular expressions. So I am not going to answer this for you. But you might find a tool like the following useful to play with regular expressions:

Also there are tons of resources out there, to read about how to use regular expressions:

您可以将负数和正数添加到单独的列表中,然后将它们分别相加,然后进行减法。

You can use regex to match the numbers that may be occurring in the string. The regex I am using is based on the assumption numbers can occur with or without a negative sign in the string.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        final String regex = "[-]*[0-9]+";
        final String string = "asd-12sdf45-56asdf100";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        int sum = 0;

        while (matcher.find()) {
            System.out.println("Found number: " + matcher.group(0));
            sum += Integer.parseInt(matcher.group(0));
        }

        System.out.println("Sum = "+sum);
    }
}

Output : 

Found number: -12
Found number: 45
Found number: -56
Found number: 100
Sum = 77

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM