Count Digits in a String in Java — Definition, Examples and Program
Counting digits in a string is a common string-processing task. It helps in validating inputs like phone numbers, IDs, and mixed text data.
In this blog, you will learn:
- What digits are
- How to count digits in a string
- Step-by-step examples
- A simple Java program
- Practice challenges
What Are Digits?
Digits are numeric characters from 0 to 9.
How the Logic Works
To count digits in a string:
- Read the input string.
- Traverse each character of the string.
- Check whether the character is between '0' and '9'.
- Increase the digit count when a digit is found.
Example 1
Input: "Java123"
- 1 → digit
- 2 → digit
- 3 → digit
Total Digits: 3
Example 2
Input: "Room No 45A"
- 4 → digit
- 5 → digit
Total Digits: 2
Java Program to Count Digits
import java.util.Scanner;
public class CountDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = sc.nextLine();
int digitCount = 0;
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch >= '0' && ch <= '9') {
digitCount++;
}
}
System.out.println("Number of digits: " + digitCount);
}
}
Sample Output
Enter a string: hospitalRoom23
Number of digits: 2
Practice Challenges
- Modify the program to count letters, digits, and special characters separately.
- Check if a string contains only digits.
- Extract all digits from a string and form a number.
Counting digits is an essential skill for input validation and string analysis in Java. It forms the basis for many real-world applications.