Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIProgram to check if input is an integer or a string

Program to check if input is an integer or a string

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>
using namespace std;
 
// Returns true if s is a number else false
bool isNumber(string s)
{
    for (int i = 0; i < s.length(); i++)
        if (isdigit(s[i]) == false)
            return false;
 
    return true;
}
 
// Driver code
int main()
{
    // 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 integer
import java.io.*;
 
public class GFG {
 
    // Returns true if s is
    // a number else false
    static boolean isNumber(String s)
    {
        for (int i = 0; i < s.length(); i++)
            if (Character.isDigit(s.charAt(i)) == false)
                return false;
 
        return true;
    }
 
    // Driver code
    static public void main(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 false
def isNumber(s):
 
    for i in range(len(s)):
        if s[i].isdigit() != True:
            return False
 
    return True
 
 
# Driver code
if __name__ == "__main__":
 
    # Store the input in a str variable
    str = "6790"
 
    # Function Call
    if isNumber(str):
        print("Integer")
 
    else:
        print("String")
 
# This code is contributed by ANKITRAI1


C#




// C# program to check if a given
// string is a valid integer
using System;
 
public class GFG {
 
    // Returns true if s is a
    // number else false
    static bool isNumber(string s)
    {
        for (int i = 0; i < s.Length; i++)
            if (char.IsDigit(s[i]) == false)
                return false;
 
        return true;
    }
 
    // Driver code
    static public void Main(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))
            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
    function isNumber(s)
    {
        for (let i = 0; i < s.length; i++)
            if (s[i] < '0' || s[i] > '9')
                return false;
  
        return true;
    }
     
    // 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 false
function isNumber($s)
{
    for ($i = 0; $i < strlen($s); $i++)
        if (is_numeric($s[$i]) == false)
            return false;
 
    return true;
}
 
// 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
?>


Output

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>
 
using namespace std;
 
// Function to determine whether
// the user input is string or integer type
bool isNumber(const string& input) {
    for (char c : input) {
        if (!isdigit(c)) {
            return false;
        }
    }
    return true;
}
 
// Driver code
int main() {
    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;
    }
 
    return 0;
}


Java




// Java program to find
// whether the user input
// is int or string type
 
public class Main {
    // Function to determine whether
    // the user input is string or
    // integer type
    public static boolean isNumber(Object x) {
        if (x instanceof Integer) {
            return true;
        } else {
            return false;
        }
    }
 
    // Driver code
    public static void main(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 type
def isNumber(x):
    if type(x) == int:
         return True
    else:
         return False
 
 
# Driver Code
input1 = 122
input2 = '122'
 
# Function Call
 
# for input1
if isNumber(input1):
    print("Integer")
else:
    print("String")
 
# for input2
if isNumber(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 type
function isNumber(x) {
    if (typeof x === 'number') {
        return true;
    } else {
        return false;
    }
}
 
// Driver Code
let input1 = 122;
let input2 = '122';
 
// Function Call
 
// for input1
if (isNumber(input1)) {
    console.log("Integer");
} else {
    console.log("String");
}
 
// for input2
if (isNumber(input2)) {
    console.log("Integer");
} else {
    console.log("String");
}


Output

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 integer
import java.io.*;
 
public class GFG {
 
    // Driver code
    static public void main(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


Output

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>
using namespace std;
 
// Function to check if st is number or not
bool isNumber(string st){
      int i = 0;
    while (st[i] != NULL) {
        if (st[i] < 48 || st[i] > 57)
            return false;
        i++;
    }
    return true;
}
 
int main(){
       
    // 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";
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Java




import java.io.*;
 
public class GFG {
    // Returns true if st is a number else false
    static boolean isNumber(String st) {
        for (int i = 0; i < st.length(); i++)
            if (st.charAt(i) < 48 || st.charAt(i) > 57)
                return false;
        return true;
    }
 
    public static void main(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 not
def isNumber(st):
    i = 0
    while i < len(st):
        if ord(st[i]) < ord("0") or ord(st[i]) > ord("9"):
            return False
        i += 1
    return True
 
if __name__ == "__main__":
    # Saving the input in a string
    st = "122B"
 
    # Function returns true if all elements are in
    # range '0-9'
    if isNumber(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#




using System;
 
public class Program {
    // Returns true if st is a number else false
    static bool isNumber(string st)
    {
        for (int i = 0; i < st.Length; i++)
            if (st[i] < 48 || st[i] > 57)
                return false;
        return true;
    }
 
    static void Main(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))
            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 not
function isNumber(st){
    let i = 0;
    while (st[i] != null) {
        if (st[i] < 48 || st[i] > 57)
            return false;
        i++;
    }
    return true;
}
 
    // Saving the input in a string
let 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 string
else
    console.log("String");


Output

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 not
def isNumber(st):
    if isinstance(st, int):
        return True
    return False
 
 
if __name__ == "__main__":
    # Saving the input in a string
    st = "122B"
    pt = 122
 
    print(st, end=': ')
    # Function returns true if st is number
    if isNumber(st):
        print("Integer")
 
    # Function returns false if st is not number
    else:
        print("String")
         
    # For 122
    print(pt, end=': ')
    if isNumber(pt):
        print("Integer")
    else:
        print("String")
 
# This code is contributed by Susobhan Akhuli


Output

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 not
def isNumber(st):
    return st.isnumeric()
 
if __name__ == "__main__":
    # Saving the input in a string
    st = "122B"
    pt = "122"
 
    print(st, end=': ')
    # Function returns true if st is number
    if isNumber(st):
        print("Integer")
 
    # Function returns false if st is not number
    else:
        print("String")
         
    # For 122
    print(pt, end=': ')
    if isNumber(pt):
        print("Integer")
    else:
        print("String")
 
# This code is contributed by Susobhan Akhuli


Output

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>
using namespace std;
 
// Function to print Integer or String according to
// boolean value
void check(bool result)
{
    if (result) {
        cout << "Integer" << endl;
    }
    else {
        cout << "String" << endl;
    }
}
 
int main()
{
    string s1 = "122B";
    string s2 = "122";
 
    // Return true if input is integer
    regex pattern("^-?\\d+$");
    bool result = regex_match(s1, pattern);
    cout << s1 << ": ";
    check(result);
 
    // Return false if input is integer
    result = regex_match(s2, pattern);
    cout << s2 << ": ";
    check(result);
 
    return 0;
}
 
// This code is contributed by Susobhan Akhuli


Java




// Java program to check if a given input is a valid integer
// or a string
 
public class GFG {
    // Function to print Integer or String according to
    // boolean value
    static void check(boolean result)
    {
        if (result)
            System.out.println("Integer");
        else
            System.out.println("String");
    }
    public static void main(String[] args)
    {
        String s1 = "122B";
        String s2 = "122";
 
        // Return true if input is integer
        boolean result = 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 string
import re
 
# Function to print Integer or String according to boolean value
def check(result):
    if result:
        print("Integer")
    else:
        print("String")
 
 
s1 = "122B"
s2 = "122"
 
# Return true if input is integer
pattern = "^-?\d+$"
result = bool(re.match(pattern, s1))
print(s1 + ": ", end="")
check(result)
 
# Return false if input is integer
result = 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 string
using System;
using System.Text.RegularExpressions;
 
class Program {
    // Function to print Integer or String according to
    // boolean value
    static void Check(bool result)
    {
        if (result) {
            Console.WriteLine("Integer");
        }
        else {
            Console.WriteLine("String");
        }
    }
 
    static void Main(string[] args)
    {
        string s1 = "122B";
        string s2 = "122";
 
        // Return true if input is integer
        Regex pattern = new Regex("^-?\\d+$");
        bool result = 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
    function check(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>


Output

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 operator
 
public class GFG {
    // Function to print Integer or String according to
    // instanceof
    static void check(Object obj)
    {
        if (obj instanceof Integer) {
            System.out.println("Integer");
        }
        else if (obj instanceof String) {
            System.out.println("String");
        }
        else {
            System.out.println("Other Type");
        }
    }
    public static void main(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


Output

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() method
 
class GFG {
    static void check(String input)
    {
        try {
            Integer.valueOf(input);
            System.out.println("Integer");
        }
        catch (NumberFormatException e) {
            System.out.println("String");
        }
    }
 
    public static void main(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


Output

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:

  1. Create an Object variable to store the input value.
  2. Use the instanceof operator to check if the input is an instance of Integer. If it is, then the input is an integer.
  3. If the input is not an instance of Integer, convert it to a string using the String.valueOf() method.
  4. 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.
  5. Create an Integer object with the parsed integer using the Integer.valueOf() method.
  6. 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() method
 
public class GFG {
    static void check(Object input)
    {
        if (input instanceof Integer) {
            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");
            }
        }
    }
    public static void main(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


Output

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:

  1. Convert the input to a string using the String.valueOf() method.
  2. 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() method
public class GFG {
    static void check(Object input)
    {
        if (input instanceof Integer) {
            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");
            }
        }
    }
    public static void main(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


Output

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. 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments