How do I calculate the sum of all the numbers in a string? In the example below, the expected result would be 4+8+9+6+3+5
. My attempt is below. Also could I calculate the sum of only those numbers which are divisible by 2?
int sum=0;
String s = "jklmn489pjro635ops";
for(int i=0; i<s.length(); i++) {
char temp = s.charAt(i);
if (Character.isDigit(temp)) {
int b = Integer.parseInt(String.valueOf(temp));
sum=sum+b;
}
}
System.out.println(sum);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…