Java How To Count Digits in a String
Count Digits in a String
Go through each character and count how many are digits (0-9).
Example
String text = "W3Schools was founded in 1998";
int count = 0;
for (char c : text.toCharArray()) {
if (Character.isDigit(c)) {
count++;
}
}
System.out.println("Digits: " + count);
Explanation: We loop through each character of the string. The method Character.isDigit()
checks if the character is a digit. For the example above, the program finds 5 digits.