Write a function to check whether a given input is an integer or a string.
Definition of an integer : 
Every element should be a valid digit, i.e ‘0-9’.
Definition of a string : 
Any one element should be an invalid digit, i.e any symbol other than ‘0-9’.
Examples:
Input : 127
Output : Integer
Explanation : All digits are in the range '0-9'.
Input : 199.7
Output : String
Explanation : A dot is present.
Input : 122B
Output : String
Explanation : A alphabet is present.
Method 1: The idea is to use isdigit() function and is_numeric() function..
Algorithm:
1. Take input string from user.
2. Initialize a flag variable “isNumber” as true.
3. For each character in the input string:
              a. If the character is not a digit, set the “isNumber” flag to false and break the loop.
4. If the “isNumber” flag is true, print “Integer.”
5. If the “isNumber” flag is false, print “String.”
Pseudocode:
inputString = readString()
isNumber = true
for character in inputString:
if !isdigit(character):
isNumber = false
break
if isNumber:
print "Integer"
else:
print "String"
Below is the implementation of the above idea.
C++
| // CPP program to check if a given string// is a valid integer#include <iostream>usingnamespacestd;// Returns true if s is a number else falseboolisNumber(string s){    for(inti = 0; i < s.length(); i++)        if(isdigit(s[i]) == false)            returnfalse;    returntrue;}// Driver codeintmain(){    // Saving the input in a string    string str = "6790";    // Function returns 1 if all elements    // are in range '0-9'    if(isNumber(str))        cout << "Integer";    // Function returns 0 if the input is    // not an integer    else        cout << "String";} | 
Java
| // Java program to check if a given// string is a valid integerimportjava.io.*;publicclassGFG {    // Returns true if s is    // a number else false    staticbooleanisNumber(String s)    {        for(inti = 0; i < s.length(); i++)            if(Character.isDigit(s.charAt(i)) == false)                returnfalse;        returntrue;    }    // Driver code    staticpublicvoidmain(String[] args)    {        // Saving the input in a string        String str = "6790";        // Function returns 1 if all elements        // are in range '0 - 9'        if(isNumber(str))            System.out.println("Integer");        // Function returns 0 if the        // input is not an integer        else            System.out.println("String");    }}// This code is contributed by vt_m. | 
Python 3
| # Python 3 program to check if a given string# is a valid integer# This function Returns true if# s is a number else falsedefisNumber(s):    fori inrange(len(s)):        ifs[i].isdigit() !=True:            returnFalse    returnTrue# Driver codeif__name__ =="__main__":    # Store the input in a str variable    str="6790"    # Function Call    ifisNumber(str):        print("Integer")    else:        print("String")# This code is contributed by ANKITRAI1 | 
C#
| // C# program to check if a given// string is a valid integerusingSystem;publicclassGFG {    // Returns true if s is a    // number else false    staticboolisNumber(strings)    {        for(inti = 0; i < s.Length; i++)            if(char.IsDigit(s[i]) == false)                returnfalse;        returntrue;    }    // Driver code    staticpublicvoidMain(String[] args)    {        // Saving the input in a string        stringstr = "6790";        // Function returns 1 if all elements        // are in range '0 - 9'        if(isNumber(str))            Console.WriteLine("Integer");        // Function returns 0 if the        // input is not an integer        else            Console.WriteLine("String");    }}// This code is contributed by vt_m. | 
Javascript
| <script>    // Javascript program to check if a given    // string is a valid integer        // Returns true if s is a    // number else false    functionisNumber(s)    {        for(let i = 0; i < s.length; i++)            if(s[i] < '0'|| s[i] > '9')                returnfalse;         returntrue;    }        // Saving the input in a string    let str = "6790";    // Function returns 1 if all elements    // are in range '0 - 9'    if(isNumber(str))      document.write("Integer");    // Function returns 0 if the    // input is not an integer    else      document.write("String");    </script> | 
PHP
| <?php// PHP program to check if a // given string is a valid integer// Returns true if s // is a number else falsefunctionisNumber($s){    for($i= 0; $i< strlen($s); $i++)        if(is_numeric($s[$i]) == false)            returnfalse;    returntrue;}// Driver code// Saving the input// in a string$str= "6790";// Function returns // 1 if all elements// are in range '0-9'if(isNumber($str))    echo"Integer";else    echo"String";// This code is contributed by ajit?> | 
Integer
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2: Using special Python built-in type() function:
type() is a built-in function provided by python . type() takes object as parameter and returns its class type as its name says.
Below is the implementation of the above idea:
C++
| #include <iostream>#include <string>usingnamespacestd;// Function to determine whether// the user input is string or integer typeboolisNumber(conststring& input) {    for(charc : input) {        if(!isdigit(c)) {            returnfalse;        }    }    returntrue;}// Driver codeintmain() {    string input1 = "122";    string input2 = "abc123";    // Function Call    // for input1    if(isNumber(input1)) {        cout << "Integer"<< endl;    } else{        cout << "String"<< endl;    }    // for input2    if(isNumber(input2)) {        cout << "Integer"<< endl;    } else{        cout << "String"<< endl;    }    return0;} | 
Java
| // Java program to find// whether the user input// is int or string typepublicclassMain {    // Function to determine whether     // the user input is string or    // integer type    publicstaticbooleanisNumber(Object x) {        if(x instanceofInteger) {            returntrue;        } else{            returnfalse;        }    }    // Driver code    publicstaticvoidmain(String[] args) {        Object input1 = 122;        Object input2 = "122";        // Function Call        // for input1        if(isNumber(input1)) {            System.out.println("Integer");        } else{            System.out.println("String");        }        // for input2        if(isNumber(input2)) {            System.out.println("Integer");        } else{            System.out.println("String");        }    }} | 
Python3
| # Python program to find# whether the user input# is int or string type# Function to determine whether # the user input is string or# integer typedefisNumber(x):    iftype(x) ==int:         returnTrue    else:         returnFalse# Driver Codeinput1 =122input2 ='122'# Function Call# for input1ifisNumber(input1):    print("Integer")else:    print("String")# for input2ifisNumber(input2):    print("Integer")else:    print("String") | 
Javascript
| // JavaScript program to find// whether the user input// is int or string type// Function to determine whether // the user input is string or// integer typefunctionisNumber(x) {    if(typeofx === 'number') {        returntrue;    } else{        returnfalse;    }}// Driver Codelet input1 = 122;let input2 = '122';// Function Call// for input1if(isNumber(input1)) {    console.log("Integer");} else{    console.log("String");}// for input2if(isNumber(input2)) {    console.log("Integer");} else{    console.log("String");} | 
Integer String
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 3: Using Integer.parseInt() in Java
The parseInt() method of Integer class is used to parse a given string into an integer provided that the string contains a valid integer. In case, the string doesn’t contain a valid integer, it throws a NumberFormatException. The idea is to parse the given string using the same. If an exception is found, then the given string will not be a valid integer and vice-versa.
Below is the implementation of the above idea:
Java
| // Java program to check if a given// string is a valid integerimportjava.io.*;publicclassGFG {    // Driver code    staticpublicvoidmain(String[] args)    {        String s = "abc"; //sample input to test        try{            Integer.parseInt(s);            System.out.println("Integer");        }catch(NumberFormatException e){            System.out.println("String");        }     }}// This code is contributed by shruti456rawal | 
String
Time Complexity: O(N) where N is the length of the string.
Auxiliary Space: O(1)
Method 4: Traverse and check if ASCII range falls under (0-9)
This method/algo is that traverse through the string and checks if ASCII range of every character falls under (0-9) or not. If every character is in range (48-57) then it prints that the string is an integer otherwise it is a string.
C++
| // CPP program to check if a given string// is a valid integer#include <iostream>usingnamespacestd;// Function to check if st is number or notboolisNumber(string st){      inti = 0;    while(st[i] != NULL) {        if(st[i] < 48 || st[i] > 57)            returnfalse;        i++;    }    returntrue;}intmain(){          // Saving the input in a string    string st = "122B";    // Function returns true if all elements are in    // range '0-9'    if(isNumber(st))        cout << "Integer";    // Function returns false if the input is not an    // integer, a string    else        cout << "String";    return0;}// This code is contributed by Susobhan Akhuli | 
Java
| importjava.io.*;publicclassGFG {    // Returns true if st is a number else false    staticbooleanisNumber(String st) {        for(inti = 0; i < st.length(); i++)            if(st.charAt(i) < 48|| st.charAt(i) > 57)                returnfalse;        returntrue;    }    publicstaticvoidmain(String[] args) {        // Saving the input in a string        String st = "122B";        // Function returns true if all elements are in        // range '0-9'        if(isNumber(st))            System.out.println("Integer");        // Function returns false if the input is not an        // integer, a string        else            System.out.println("String");    }}// This code is contributed by Susobhan Akhuli | 
Python3
| # Python program to check if a given string# is a valid integer# Function to check if st is number or notdefisNumber(st):    i =0    whilei < len(st):        iford(st[i]) < ord("0") orord(st[i]) > ord("9"):            returnFalse        i +=1    returnTrueif__name__ =="__main__":    # Saving the input in a string    st ="122B"    # Function returns true if all elements are in    # range '0-9'    ifisNumber(st):        print("Integer")    # Function returns false if the input is not an    # integer, a string    else:        print("String")# This code is contributed by Susobhan Akhuli | 
C#
| usingSystem;publicclassProgram {    // Returns true if st is a number else false    staticboolisNumber(stringst)    {        for(inti = 0; i < st.Length; i++)            if(st[i] < 48 || st[i] > 57)                returnfalse;        returntrue;    }    staticvoidMain(string[] args)    {        // Saving the input in a string        stringst = "122B";        // Function returns true if all elements are in        // range '0-9'        if(isNumber(st))            Console.WriteLine("Integer");        // Function returns false if the input is not an        // integer, a string        else            Console.WriteLine("String");    }} | 
Javascript
| // Javascript program to check if a given string// is a valid integer// Function to check if st is number or notfunctionisNumber(st){    let i = 0;    while(st[i] != null) {        if(st[i] < 48 || st[i] > 57)            returnfalse;        i++;    }    returntrue;}    // Saving the input in a stringlet st = "122B";// Function returns true if all elements are in// range '0-9'if(isNumber(st))    console.log("Integer");// Function returns false if the input is not an// integer, a stringelse    console.log("String"); | 
String
Time Complexity: O(N) where N is the length of the string.
Auxiliary Space: O(1)
Method 5: Using isinstance() in Python
The isinstance() method is a built-in function in Python that checks whether an object is an instance of a specified class. It returns a boolean value, True if the object is an instance of the class, False otherwise. It takes two arguments, the object and the class, and returns True or False depending on the object’s class.
For example, isinstance(3, int) will return True, while isinstance(‘abc’, int) will return False.
Python3
| # Python program to check if a given input# is a valid integer or a string# Function to check if st is number or notdefisNumber(st):    ifisinstance(st, int):        returnTrue    returnFalseif__name__ =="__main__":    # Saving the input in a string    st ="122B"    pt =122    print(st, end=': ')    # Function returns true if st is number    ifisNumber(st):        print("Integer")    # Function returns false if st is not number    else:        print("String")            # For 122    print(pt, end=': ')    ifisNumber(pt):        print("Integer")    else:        print("String")# This code is contributed by Susobhan Akhuli | 
122B: String 122: Integer
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 6: Using isnumeric() in Python
The isnumeric() method returns True if all the characters in a string are numeric characters. This includes any characters that can be used to form the base 10 numeric system, such as digits 0 to 9, negative sign, decimal point, etc. It returns False if any character is not a numeric character.
Python3
| # Python program to check if a given input# is a valid integer or a string# Function to check if st is number or notdefisNumber(st):    returnst.isnumeric()if__name__ =="__main__":    # Saving the input in a string    st ="122B"    pt ="122"    print(st, end=': ')    # Function returns true if st is number    ifisNumber(st):        print("Integer")    # Function returns false if st is not number    else:        print("String")            # For 122    print(pt, end=': ')    ifisNumber(pt):        print("Integer")    else:        print("String")# This code is contributed by Susobhan Akhuli | 
122B: String 122: Integer
Time Complexity: O(N), where N is the length of the input string.
Auxiliary Space: O(1)
Method 7: Using Regular Expressions
Regular expressions can be used to check if a given string is a valid integer. Regular expressions allow you to define a pattern of characters and then check if a string matches that pattern. If the string matches the pattern, it is a valid integer.
C++
| // CPP program to check if a given input is a valid integer// or a string#include <iostream>#include <regex>#include <string>usingnamespacestd;// Function to print Integer or String according to// boolean valuevoidcheck(boolresult){    if(result) {        cout << "Integer"<< endl;    }    else{        cout << "String"<< endl;    }}intmain(){    string s1 = "122B";    string s2 = "122";    // Return true if input is integer    regex pattern("^-?\\d+$");    boolresult = regex_match(s1, pattern);    cout << s1 << ": ";    check(result);    // Return false if input is integer    result = regex_match(s2, pattern);    cout << s2 << ": ";    check(result);    return0;}// This code is contributed by Susobhan Akhuli | 
Java
| // Java program to check if a given input is a valid integer// or a stringpublicclassGFG {    // Function to print Integer or String according to    // boolean value    staticvoidcheck(booleanresult)    {        if(result)            System.out.println("Integer");        else            System.out.println("String");    }    publicstaticvoidmain(String[] args)    {        String s1 = "122B";        String s2 = "122";        // Return true if input is integer        booleanresult = s1.matches("^-?\\d+$"); // True        System.out.print(s1 + ": ");        check(result);        // Return false if input is integer        result = s2.matches("^-?\\d+$"); // False        System.out.print(s2 + ": ");        check(result);    }}// This code is contributed by Susobhan Akhuli | 
Python3
| # Python program to check if a given input is a valid integer# or a stringimportre# Function to print Integer or String according to boolean valuedefcheck(result):    ifresult:        print("Integer")    else:        print("String")s1 ="122B"s2 ="122"# Return true if input is integerpattern ="^-?\d+$"result =bool(re.match(pattern, s1))print(s1 +": ", end="")check(result)# Return false if input is integerresult =bool(re.match(pattern, s2))print(s2 +": ", end="")check(result)# This code is contributed by Susobhan Akhuli | 
C#
| // C# program to check if a given input is a valid integer// or a stringusingSystem;usingSystem.Text.RegularExpressions;classProgram {    // Function to print Integer or String according to    // boolean value    staticvoidCheck(boolresult)    {        if(result) {            Console.WriteLine("Integer");        }        else{            Console.WriteLine("String");        }    }    staticvoidMain(string[] args)    {        strings1 = "122B";        strings2 = "122";        // Return true if input is integer        Regex pattern = newRegex("^-?\\d+$");        boolresult = pattern.IsMatch(s1);        Console.Write(s1 + ": ");        Check(result);        // Return false if input is integer        result = pattern.IsMatch(s2);        Console.Write(s2 + ": ");        Check(result);    }}// This code is contributed by Susobhan Akhuli | 
Javascript
| <script>    // Javascript program to check if a given input is a valid integer    // or a string    // Function to print Integer or String according to boolean value    functioncheck(result) {        if(result) {            document.write("Integer<br>");        } else{            document.write("String<br>");        }    }        let s1 = "122B";    let s2 = "122";        // Return true if input is integer    let pattern = "^-?\\d+$";    let result = Boolean(s1.match(pattern));    document.write(s1 + ": ", end="");    check(result);        // Return false if input is integer    result = Boolean(s2.match(pattern));    document.write(s2 + ": ", end="");    check(result);        // This code is contributed by Susobhan Akhuli</script> | 
122B: String 122: Integer
Time Complexity: O(N), where N is the length of the input.
Auxiliary Space: O(1)
Method 8: Using Java instanceof operator
The instanceof operator is used to check if an object is an instance of a particular type. It takes two parameters: the object to be checked and the type to be checked against. It returns a boolean value indicating whether the object is an instance of the specified type.
Java
| // Java program to check if a given input is a valid integer// or a string using instanceof operatorpublicclassGFG {    // Function to print Integer or String according to    // instanceof    staticvoidcheck(Object obj)    {        if(obj instanceofInteger) {            System.out.println("Integer");        }        elseif(obj instanceofString) {            System.out.println("String");        }        else{            System.out.println("Other Type");        }    }    publicstaticvoidmain(String[] args)    {        Object s1 = "122B";        Object s2 = 122;        System.out.print(s1 + ": ");          // Print according to instanceof        check(s1);                  System.out.print(s2 + ": ");          // Print according to instanceof        check(s2);    }}// This code is contributed by Susobhan Akhuli | 
122B: String 122: Integer
Time Complexity: O(1), because there is no loop or recursion in the code. The code is a simple if-else statement which takes a constant amount of time to execute.
Auxiliary Space: O(1), because there is no extra space required to execute this code. The only variables used in this code are s1, s2, and obj, and they all take constant space.
Method 9: Using Java Integer.valueOf() method
The Integer.valueOf() method is used to check if the given input is an integer or a string. If the input is an integer, then it will return the integer value, otherwise it will throw a NumberFormatException, which can be caught and used to determine that the input is a string.
Java
| // Java program to check if a given input is a valid integer// or a string using Integer.valueOf() methodclassGFG {    staticvoidcheck(String input)    {        try{            Integer.valueOf(input);            System.out.println("Integer");        }        catch(NumberFormatException e) {            System.out.println("String");        }    }    publicstaticvoidmain(String[] args)    {        String s1 = "122B";        String s2 = "122";                  System.out.print(s1 + ": ");        check(s1);        System.out.print(s2 + ": ");        check(s2);    }}// This code is contributed by Susobhan Akhuli | 
122B: String 122: Integer
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 10: Using Java Integer.equals() method
The Integer.equals() method is used to check if the given input is an integer or a string.
Steps:
To check if an input is an integer or a string using the Integer.equals() method in Java, you can follow these steps:
- Create an Object variable to store the input value.
- Use the instanceof operator to check if the input is an instance of Integer. If it is, then the input is an integer.
- If the input is not an instance of Integer, convert it to a string using the String.valueOf() method.
- Use the try-catch block to parse the input string into an integer using the Integer.parseInt() method. If the input string is not a valid integer, catch the NumberFormatException.
- Create an Integer object with the parsed integer using the Integer.valueOf() method.
- Check if the Integer object is equal to the input object using the Integer.equals() method. If they are equal, then the input is an integer. If they are not equal, then the input is a string.
Below is the implementation of the above approach:
Java
| // Java program to check if a given input is a valid integer// or a string using integer.equals() methodpublicclassGFG {    staticvoidcheck(Object input)    {        if(input instanceofInteger) {            System.out.println("Input is an integer");        }        else{            try{                String str = String.valueOf(input);                Integer num = Integer.valueOf(str);                if(num.equals(input)) {                    System.out.println(                        "Input is an integer");                }                else{                    System.out.println("Input is a string");                }            }            catch(NumberFormatException e) {                System.out.println("Input is a string");            }        }    }    publicstaticvoidmain(String[] args)    {        Object s1 = "122B";        Object s2 = 122;        System.out.print(s1 + ": ");        check(s1);        System.out.print(s2 + ": ");        check(s2);    }}// This code is contributed by Susobhan Akhuli | 
122B: Input is a string 122: Input is an integer
Time Complexity: O(N), where N is the length of the input string, because it performs string operations such as converting the input to a string and parsing the string into an integer.
Auxiliary Space: O(N), as it uses a string variable to store the input as a string and an Integer object to store the input as an integer.
Method 11: Using Java Integer.compare() Method
The Integer.compare() method is used to check if the given input is an integer or a string.
Steps:
To check if an input is an integer or a string using the Integer.compare() method in Java, we can do the
following:
- Convert the input to a string using the String.valueOf() method.
- Compare the input string to the string representation of its integer value using the Integer.compare() method. 
- If the two strings are equal, then the input is an integer.
- If the two strings are not equal, then the input is a string.
 
Below is the implementation of the above approach:
Java
| // Java program to check if a given input is a valid integer// or a string using integer.equals() methodpublicclassGFG {    staticvoidcheck(Object input)    {        if(input instanceofInteger) {            System.out.println("Input is an integer");        }        else{            try{                String str = String.valueOf(input);                if(Integer.compare(Integer.parseInt(str),                                    (Integer)input)                    == 0) {                    System.out.println(                        "Input is an integer");                }                else{                    System.out.println("Input is a string");                }            }            catch(NumberFormatException e) {                System.out.println("Input is a string");            }        }    }    publicstaticvoidmain(String[] args)    {        Object s1 = "122B";        Object s2 = 122;        System.out.print(s1 + ": ");        check(s1);        System.out.print(s2 + ": ");        check(s2);    }}// This code is contributed by Susobhan Akhuli | 
122B: Input is a string 122: Input is an integer
Time Complexity: O(n), where n is the length of the input string, because it performs string operations such as converting the input to a string and comparing two strings.
Auxiliary Space: O(n), as it uses a string variable to store the input as a string.
This article is contributed by Rohit Thapliyal. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!


 
                                    







