Summing digits of an alphanumeric string I am going through the Java CodingBat exercises. Here is the one I have just completed:


  Given a string, return the sum of the digits 0-9 that appear in the string, ignoring all other characters. Return 0 if there are no digits in the string.


Here is my code:

public int sumDigits(String str) {

    StringBuilder strAppend = new StringBuilder();

    for (int i = 0; i &lt; str.length(); i++) {
        if (Character.isDigit(str.charAt(i))) {
            strAppend.append(str.charAt(i));
        }
    }

    int total = 0;
    String strDigits = strAppend.toString();

    for (int i = 0; i &lt; strDigits.length(); i++) {
        total += Integer.parseInt(strDigits.substring(i, i+1));
    }

    return total;

}


My questions are:


Should I be using one for loop instead of two?
Is it correct to be converting to StringBuilder to avoid concatenating a string?
Is it right to convert from string to int towards the end of the method, or convert as the digits are found?
Your question is surprising in the sense that you use the somewhat obscure isDigit method (not many people are aware of that one), yet you do not use the similar Character.getNumericValue(...) method.

Using that method, you can remove the second loop (as you suspected). It also answers the second question - there is no need for a StringBuilder, or the int conversion:

int total = 0;
for (char c : str.toCharArray()) {
    if (Character.isDigit(c)) {
        total += Character.getNumericValue(c);
    }
}
return total;