patternjavaModerate
Summing digits of an alphanumeric string
Viewed 0 times
summingdigitsstringalphanumeric
Problem
I am going through the Java CodingBat exercises. Here is the one I have just completed:
Given a
Here is my code:
My questions are:
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 < 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 < strDigits.length(); i++) {
total += Integer.parseInt(strDigits.substring(i, i+1));
}
return total;
}My questions are:
- Should I be using one
forloop instead of two?
- Is it correct to be converting to
StringBuilderto avoid concatenating astring?
- Is it right to convert from
stringtointtowards the end of the method, or convert as the digits are found?
Solution
Your question is surprising in the sense that you use the somewhat obscure
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:
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;Code Snippets
int total = 0;
for (char c : str.toCharArray()) {
if (Character.isDigit(c)) {
total += Character.getNumericValue(c);
}
}
return total;Context
StackExchange Code Review Q#86726, answer score: 11
Revisions (0)
No revisions yet.