我有一个字符串,其中包含数字和字符以及特殊符号。但我需要计算字符串中的数字总和。 假设我的字符串是
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/