Count number of digits in a given string in Java [2 ways]

In this post, I will be sharing how to count number of digits in a given string in Java. I have already shared why Strings are immutable in Java. There are two ways to achieve our goal:

1. Using isDigit() method [Easiest]

2. Using ASCII values

Read Also: Check String Contains Special Characters in Java

Let's understand the question first with the help of examples:

 InputString:  1Alive12is123Awesome1234Learn12345Java
Output: 15
InputString: Java9Programming1011
Output: 5

Count number of digits in a given string in Java

1. Using isDigit() method


Algorithm:


1. We will traverse each character of the given string using for loop.
2. Checking if character is digit or not using Character.isDigit() method.
3. Initialize count variable to count the number of digits in the given string.
4. Print the value of count variable.

Java Program


 public class CountDigits {
    public static void main(String args[]) {
      
      // Given InputString
      String str = "1Alive12is123Awesome1234Learn12345Java";
      
      // Initializing count variable    
      int count = 0; 
      
      for(int i=0; i < str.length(); i++) {
          if(Character.isDigit(str.charAt(i))) {
              count++;
          }
      }
      
      // Printing the number of digits in a given string 
      System.out.println("Number of digits in the given string is: "+ count);
    }
}


Output:
Number of digits in the given string is: 15


2. Using ASCII values


Algorithm:


1. Initialize one integer variable with value 0.
2. Start traversing the given string.
3. If the ASCII value of the character at current index is in the range of 48(inclusive) and 57(inclusive) then increment the value of integer variable by 1.
4. After the traversal of given string, print the integer variable.

Java Program


 public class CountDigits2 {
    public static void main(String args[]) {
      
      // Given input string 
      String str = "Java9Programming1011";
      
      // Initializing integer variable    
      int count = 0; 
      int asciiValue = 0;
      for(int i=0; i < str.length(); i++) {
          asciiValue = (int) str.charAt(i);
          if(asciiValue >= 48 && asciiValue <= 57) {
              count++;
          }
      }
      
      // Printing the number of digits in a given string 
      System.out.println("Number of digits in the given string is: "+ count);
    }
}


Output:
Number of digits in the given string is: 5


That's all for today. Please mention in the comments if you have any questions related to how to count number of digits in a given string in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry