Related Articles

• Write an Interview Experience
• String Data Structure

Program to check if input is an integer or a string

• Difficulty Level : Easy
• Last Updated : 30 Jan, 2023

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

Below is the implementation of the above idea.

C++

 `// CPP program to check if a given string``// is a valid integer``#include ``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.`

PHP

 ``

Javascript

 ``

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:

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

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 ``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)

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks 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 GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up