Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Program to Count Number of Digits in a String

  • Difficulty Level : Easy
  • Last Updated : 30 Apr, 2021

The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it’s content can’t change. Complete traversal in the string is required to find the total number of digits in a string.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Input : string = "GeeksforGeeks password is : 1234"
Output: Total number of Digits = 4

Input : string = "G e e k s f o r G e e k 1234"
Output: Total number of Digits = 4

Approach:

  1. Create one integer variable and initialize it with 0.
  2. Start string traversal.
  3. If the ASCII code of character at the current index is greater than or equals to 48 and less than or equals to 57 then increment the variable.
  4. After the end of the traversal, print variable.

Below is the implementation of the above approach:



Java




// Java Program to Count Number of Digits in a String
public class GFG {
 
    public static void main(String[] args)
    {
        String str = "GeeksforGeeks password is : 1234";
        int digits = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) >= 48 && str.charAt(i) <= 57)
                digits++;
        }
        System.out.println("Total number of Digits = "
                           + digits);
    }
}

 
 

Output
Total number of Digits = 4

 

Time Complexity: O(N), where N is the length of the string.

 

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!