SwadhyAI Notes

All Java notes

How to Count Digits in a String in Java

The Challenge

Count how many numeric digits (0-9) are in a string!

Solution

Method 1: Using Character.isDigit()

java
String text = "Hello123World456";
int digitCount = 0;

for (int i = 0; i < text.length(); i++) {
    if (Character.isDigit(text.charAt(i))) {
        digitCount++;
    }
}

System.out.println("Digit count: " + digitCount);
// Output: Digit count: 6

Method 2: Using Regex

java
String text = "Hello123World456";
int digitCount = text.replaceAll("[^0-9]", "").length();

System.out.println("Digit count: " + digitCount);
// Output: Digit count: 6

Method 3: Using Java 8 Streams

java
String text = "Hello123World456";
long digitCount = text.chars()
                      .filter(Character::isDigit)
                      .count();

System.out.println("Digit count: " + digitCount);
// Output: Digit count: 6

Did You Know?

Character.isDigit() works with Unicode digits from any language, not just 0-9! For strict 0-9 checking, use c >= '0' && c <= '9'.

Pro Tip

Extract all digits from a string:

java
String text = "Price: $123.45";
String digits = text.replaceAll("[^0-9]", "");
System.out.println(digits); // 12345

Real-World Use Cases

  • Password validation: Ensure passwords contain numbers
  • Data extraction: Extract numeric data from text
  • Input validation: Check if input contains digits
  • Text analysis: Analyze alphanumeric content
›Short versionOpen if you only have a minute.
  • Walk the string and count characters that are digits. Do not parse the whole string.
  • Integer.parseInt("A12B3") throws. The text was never a single number.
  • Character.isDigit is true for more than '0' through '9', including many Unicode digits.
  • A leading minus and a decimal point are not digits.

Count digits in text

Count digit characters inside a string.

Working approach

  • Loop with charAt.
  • Use c >= '0' && c <= '9' when the task means ASCII digits.
  • Use Character.isDigit only when other Unicode digits should count.

Walk the sample

  1. Input "A12B3"
  2. A is skipped, 1 and 2 count, B is skipped, 3 counts
  3. The count is 3

The trap

Character.isDigit('\u0663') is true. That character is an Arabic-Indic digit, not the ASCII character 3. A parser that meant 0-9 will over-count.

java
static int asciiDigits(String text) {
    int count = 0;
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (c >= '0' && c <= '9') {
            count++;
        }
    }
    return count;
}

Does Character.isDigit count only the characters 0 through 9?

No. It returns true for any character whose Unicode category is a digit, including Arabic-Indic digits.

The range check against '0' and '9' matches the ASCII digits this kind of exercise is usually asking about.

Time O(n), space O(1).

Easy to get wrong

  • Parsing the whole string with parseInt when the text is mixed.
  • Assuming isDigit means ASCII.