我有一个字符串,其中包含数字和字符以及特殊符号。但是我需要计算字符串中的数字总和。
假设我的字符串是

String input = "step@12test_demo,9,8*#1234/add2doe";


结果应该是12 + 9 + 8 + 1234 + 2 = 1265,但是对于我的代码,我得到的结果是1 + 2 + 9 + 8 + 1 + 2 + 3 + 4 + 2 = 32。这是我的代码

public class sumOfNumInString {
    public static void main(String[] args) {
        String input = "step@12test_demo,9,8*#1234/add2doe";
        String output = "";
        int temp = input.length();
        for (int i = 0; i < temp; i++) {
            Character c = input.charAt(i);
            if (Character.isDigit(c)) {
                output = output + c;
            }
        }
        int result = Integer.parseInt(output);
        System.out.println(result);
        int num = result, sum = 0, r;
        for (; num != 0; num = num / 10) {
            r = num % 10;
            sum = sum + r;
        }
        System.out.println("Sum of digits of number: " + sum);//32
        //Need output as :12+9+8+1234+2=  1265
    }
}

最佳答案

您需要标识要添加的数字序列,因为当前正在将单个字符添加为数字。将字符串与正则表达式匹配以提取数字,然后对其进行解析和添加即可。

private static final Pattern pattern = Pattern.compile("\\d+");

public static int total(String input) {
    Matcher matcher = pattern.matcher(input);
    int total = 0;

    while (matcher.find()) {
        total += Integer.parseInt(matcher.group(0));
    }

    return total;
}


当使用您的输入字符串调用时,返回1265。

感谢弗朗切斯科的小费!

10-01 03:26
查看更多