bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java How To's
Java•Java How To's

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 = "ExampleSite 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.

Previous

Java How To Remove Vowels from a String

Next

Java How To Reverse a String