简体   繁体   English

在字符串中查找 NUMBERS 的总和?

[英]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.我必须在包含“az”、“0-9”和“-”的字符串中找到数字的总和,如果数字前有“-”,我将此数字视为负数。 For example I have this text:例如我有这样的文字:

asd-12sdf45-56asdf100 , the sum of numbers -12,45,-56 and 100 is 77 . asd-12sdf45-56asdf100 ,数字-12,45,-56 and 100的总和是77

I managed to replace all the letters and it came out -12 45-56 100 , and I am stuck here.我设法替换了所有字母,结果是-12 45-56 100 ,我被困在这里。 I tried splitting into array and then parseInt , I tried some things with loops, but dead end... Any help?我尝试拆分为数组然后parseInt ,我尝试了一些循环的东西,但死胡同......有帮助吗?

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! PS:我仍处于 IT 教育的开始阶段,因此请尽可能简单:D 提前致谢!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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