java - 字符串中的数字总和无法正常工作

标签 java string

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

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。

感谢 Francesco 的提示!

关于java - 字符串中的数字总和无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408131/

相关文章:

java - JS push、concat、unshift 的 java 等价物是什么?

java - AIX 服务器中的 IBM java 堆内存问题

java - JTable 中的 setPreferredScrollableViewportSize() 与 setFillsViewportHeight()

c++ - 如何在 C++ 中的同一函数中使用字符串和 double

javascript - 如何检查我的字符串是否包含 JavaScript 中的句点?

java catch block 导致多个输出

Java 应用程序作为系统服务

不使用 strlen() 函数计算字符串长度

javascript - 如何检查字符串是否包含 JavaScript 中的特定单词

c++ - 挣扎于文本计数器