The problem is stated as follows:
Given a string, return the sum of the numbers appearing in the string, ignoring all other characters. A number is a series of 1 or more digit chars in a row. (Note: Character.isDigit(char) tests if a char is one of the chars '0', '1', .. '9'. Integer.parseInt(string) converts a string to an int.)
sumNumbers("abc123xyz") → 123
sumNumbers("aa11b33") → 44
sumNumbers("7 11") → 18
Here's the program I wrote based on Character.isDigit(char)
and Integer.parseInt(string)
.
public int sumNumbers(String str) {
int sum = 0;
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
int count = 0;
for (int j = i; j < str.length(); j++) {
if (Character.isDigit(str.charAt(j))) count++;
else break;
}
sum += Integer.parseInt(str.substring(i, i + count));
i += count;
}
}
return sum;
}
I'm not sure if I should make it more modular since it's pretty straightforward. I was wondering if I could do this without count
. Also, I know it's nit-picky, but I want to know if the way I format my for loops and if else statements is good style. This is just a standalone program, so I'm not really concerned about the public/private issue.