我有一個字符串,它包含數字和字符以及特殊符號。但我需要計算一個字符串內的數字的總和。 假設我的字符串是字符串中的數字總和不正常
String input = "[email protected]_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 = "[email protected]_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
}
}
的圖案也可以被寫爲:'\\ d +'。然後while循環變爲'while(m.find())int current = Integer.parseInt(m.group()); \t \t \t total + = current; \t \t \t}' – 2015-02-09 11:11:29
不錯的改進。 TBH我應該從一開始就尋找這個實現 - perl和類似的方法可以在一次調用中輕鬆地從字符串中獲取每個匹配。 – 2015-02-09 11:15:08
最後要做的就是擺脫'current'變量。 – 2015-02-09 11:17:32