Skip to content
Related Articles

Related Articles

Java Program to Count Number of Digits in a String
  • Difficulty Level : Easy
  • Last Updated : 28 Dec, 2020

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:

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"
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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Count Number of Digits in a String
public class GFG {
  
    public static void main(String[] args)
    {
        String str = "GeeksforGeeks password is : 1239";
        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);
    }
}

chevron_right


Output

Total number of Digits = 4

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

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :