Skip to main content

Check if a string contains only digits

 In this program, we have to check whether a string consists of only digits (i.e. 0,1,2.....9).

eg:-

  • "qwerty" ( the given string contains characters, not digits ) print No.
  • "123e" ( there is a character present in the given string ) print No.
  • "995765" (the given string contains only digits, no any characters are present ) print Yes.


How to approach :- 

Traverse through each character of the string and for each character check whether it is a digit or not.

Now the question is " How to check a character in the given string is alphabet or digit ? "
We can check this by 2 methods :--
1. Check using ASCII value:--    
  • If the ASCII value of a character is between 48 to 57 (including both 48 and 57)  then it is a digit (0,1,2,3,....,8,9).  
        
  •   If the ASCII value of a character is between 65 to 90 (including both 65 and 90)  then it is a uppercase alphabet (A,B,C,D,....,Y,Z). 
  •   If the ASCII value of a character is between 97 to 122 (including both 97 and 122)  then it is a lowercase alphabet (a,b,c,d,....,y,z).
  

2. Direct check:--    You can also check by using the character value itself. 
    like     char < '9'  , char > '0'
               char > 'A'  , char < 'a'     etc.


In Python, we have a function with the name "isdigit( )". It checks whether the calling character is digit or alphabet.

Java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 import java.util.Scanner;
 public class CheckStringContainsOnlyDigit {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = sc.nextLine();
        int i = 0;
        for (i = 0; i < str.length(); i++) {
            if (str.charAt(i) < 47 || str.charAt(i) > 58) {
                System.out.println("String Doesn't Contains only Digit");
                break;
            }
        }
        if (i == str.length()) {
            System.out.println("String Only Contains Digit");
        }
    }
 }

Python

def checkDigits(input_str):
    for char in input_str:
        if char.isdigit()==False:
            return False
    return True
input_str = input("Enter a string:")
print(checkDigits(input_str))