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 = "Lazyroar 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:
- Create one integer variable and initialize it with 0.
- Start string traversal.
- 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.
- 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 = "Lazyroar 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); } } |
Total number of Digits = 4
Time Complexity: O(N), where N is the length of the string.
Approach : Using isDigit() method
Java
// Java Program to Count Number of Digits in a String public class GFG { public static void main(String[] args) { String str = "Lazyroar password is : 1234" ; int digits = 0 ; for ( int i = 0 ; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) digits++; } System.out.println( "Total number of Digits = " + digits); } } |
Total number of Digits = 4
Approach : Using contains() method and ArrayList
Java
// Java Program to Count Number of Digits in a String import java.lang.*; import java.util.*; public class Main{ public static void main(String[] args) { String str = "Lazyroar password is : 1234" ; String num= "0123456789" ; ArrayList<Character> numbers= new ArrayList<>(); for ( int i= 0 ;i<num.length();i++) { numbers.add(num.charAt(i)); } int digits = 0 ; for ( int i = 0 ; i < str.length(); i++) { if (numbers.contains(str.charAt(i))) digits++; } System.out.println( "Total number of Digits = " + digits); } } |
Total number of Digits = 4