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++
#include <iostream>
using namespace std;
bool isNumber(string s)
{
for ( int i = 0; i < s.length(); i++)
if ( isdigit (s[i]) == false )
return false ;
return true ;
}
int main()
{
string str = "6790" ;
if (isNumber(str))
cout << "Integer" ;
else
cout << "String" ;
}
|
Java
import java.io.*;
public class GFG {
static boolean isNumber(String s)
{
for ( int i = 0 ; i < s.length(); i++)
if (Character.isDigit(s.charAt(i)) == false )
return false ;
return true ;
}
static public void main(String[] args)
{
String str = "6790" ;
if (isNumber(str))
System.out.println( "Integer" );
else
System.out.println( "String" );
}
}
|
C#
using System;
public class GFG {
static bool isNumber( string s)
{
for ( int i = 0; i < s.Length; i++)
if ( char .IsDigit(s[i]) == false )
return false ;
return true ;
}
static public void Main(String[] args)
{
string str = "6790" ;
if (isNumber(str))
Console.WriteLine( "Integer" );
else
Console.WriteLine( "String" );
}
}
|
Javascript
<script>
function isNumber(s)
{
for (let i = 0; i < s.length; i++)
if (s[i] < '0' || s[i] > '9' )
return false ;
return true ;
}
let str = "6790" ;
if (isNumber(str))
document.write( "Integer" );
else
document.write( "String" );
</script>
|
PHP
<?php
function isNumber( $s )
{
for ( $i = 0; $i < strlen ( $s ); $i ++)
if ( is_numeric ( $s [ $i ]) == false)
return false;
return true;
}
$str = "6790" ;
if (isNumber( $str ))
echo "Integer" ;
else
echo "String" ;
?>
|
Python 3
def isNumber(s):
for i in range ( len (s)):
if s[i].isdigit() ! = True :
return False
return True
if __name__ = = "__main__" :
str = "6790"
if isNumber( str ):
print ( "Integer" )
else :
print ( "String" )
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Method 2: Using special built-in type() function:
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;
bool isNumber( const string& input) {
for ( char c : input) {
if (! isdigit (c)) {
return false ;
}
}
return true ;
}
int main() {
string input1 = "122" ;
string input2 = "abc123" ;
if (isNumber(input1)) {
cout << "Integer" << endl;
} else {
cout << "String" << endl;
}
if (isNumber(input2)) {
cout << "Integer" << endl;
} else {
cout << "String" << endl;
}
return 0;
}
|
Java
public class Main {
public static boolean isNumber(Object x) {
if (x instanceof Integer) {
return true ;
} else {
return false ;
}
}
public static void main(String[] args) {
Object input1 = 122 ;
Object input2 = "122" ;
if (isNumber(input1)) {
System.out.println( "Integer" );
} else {
System.out.println( "String" );
}
if (isNumber(input2)) {
System.out.println( "Integer" );
} else {
System.out.println( "String" );
}
}
}
|
C#
using System;
class Program {
static bool IsNumber( string input)
{
foreach ( char c in input)
{
if (!Char.IsDigit(c)) {
return false ;
}
}
return true ;
}
static void Main()
{
string input1 = "122" ;
string input2 = "abc123" ;
if (IsNumber(input1)) {
Console.WriteLine( "Integer" );
}
else {
Console.WriteLine( "String" );
}
if (IsNumber(input2)) {
Console.WriteLine( "Integer" );
}
else {
Console.WriteLine( "String" );
}
}
}
|
Javascript
function isNumber(x) {
if ( typeof x === 'number' ) {
return true ;
} else {
return false ;
}
}
let input1 = 122;
let input2 = '122' ;
if (isNumber(input1)) {
console.log( "Integer" );
} else {
console.log( "String" );
}
if (isNumber(input2)) {
console.log( "Integer" );
} else {
console.log( "String" );
}
|
Python3
def isNumber(x):
if type (x) = = int :
return True
else :
return False
input1 = 122
input2 = '122'
if isNumber(input1):
print ( "Integer" )
else :
print ( "String" )
if isNumber(input2):
print ( "Integer" )
else :
print ( "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:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
striang s = "abc" ;
try {
int result = stoi(s);
cout << "Integer" << endl;
}
catch (invalid_argument const & e) {
cout << "String" << endl;
}
catch (out_of_range const & e) {
cout << "String" << endl;
}
return 0;
}
|
Java
import java.io.*;
public class GFG {
static public void main(String[] args)
{
String s = "abc" ;
try {
Integer.parseInt(s);
System.out.println( "Integer" );
} catch (NumberFormatException e){
System.out.println( "String" );
}
}
}
|
C#
using System;
class Program
{
static void Main()
{
string s = "abc" ;
try
{
int result = int .Parse(s);
Console.WriteLine( "Converted to Integer: " + result);
}
catch (FormatException)
{
Console.WriteLine( "String" );
}
catch (OverflowException)
{
Console.WriteLine( "String" );
}
}
}
|
Javascript
let s = "abc" ;
let result = parseInt(s);
if (isNaN(result)) {
console.log( "String" );
} else {
console.log( "Integer" );
}
|
Python3
s = "abc"
try :
result = int (s)
print ( "Integer" )
except ValueError:
print ( "String" )
except OverflowError:
print ( "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++
#include <iostream>
using namespace std;
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(){
string st = "122B" ;
if (isNumber(st))
cout << "Integer" ;
else
cout << "String" ;
return 0;
}
|
Java
import java.io.*;
public class GFG {
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) {
String st = "122B" ;
if (isNumber(st))
System.out.println( "Integer" );
else
System.out.println( "String" );
}
}
|
C#
using System;
public class Program {
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)
{
string st = "122B" ;
if (isNumber(st))
Console.WriteLine( "Integer" );
else
Console.WriteLine( "String" );
}
}
|
Javascript
function isNumber(st){
let i = 0;
while (st[i] != null ) {
if (st[i] < 48 || st[i] > 57)
return false ;
i++;
}
return true ;
}
let st = "122B" ;
if (isNumber(st))
console.log( "Integer" );
else
console.log( "String" );
|
Python3
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__" :
st = "122B"
if isNumber(st):
print ( "Integer" )
else :
print ( "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
def isNumber(st):
if isinstance (st, int ):
return True
return False
if __name__ = = "__main__" :
st = "122B"
pt = 122
print (st, end = ': ' )
if isNumber(st):
print ( "Integer" )
else :
print ( "String" )
print (pt, end = ': ' )
if isNumber(pt):
print ( "Integer" )
else :
print ( "String" )
|
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.
C++
#include <bits/stdc++.h>
using namespace std;
bool isNumber(string st)
{
for ( char c : st)
if (! isdigit (c))
return false ;
return true ;
}
int main()
{
string st = "122B" ;
string pt = "122" ;
cout << st << ": " ;
if (isNumber(st))
cout << "Integer" << endl;
else
cout << "String" << endl;
cout << pt << ": " ;
if (isNumber(pt))
cout << "Integer" << endl;
else
cout << "String" << endl;
return 0;
}
|
Java
public class GFG {
static boolean isNumber(String st)
{
for ( char c : st.toCharArray()) {
if (!Character.isDigit(c)) {
return false ;
}
}
return true ;
}
public static void main(String[] args)
{
String st = "122B" ;
String pt = "122" ;
System.out.print(st + ": " );
if (isNumber(st))
System.out.println( "Integer" );
else
System.out.println( "String" );
System.out.print(pt + ": " );
if (isNumber(pt))
System.out.println( "Integer" );
else
System.out.println( "String" );
}
}
|
C#
using System;
class Program {
static bool IsNumber( string st)
{
foreach ( char c in st)
{
if (!Char.IsDigit(c))
return false ;
}
return true ;
}
static void Main( string [] args)
{
string st = "122B" ;
string pt = "122" ;
Console.Write(st + ": " );
if (IsNumber(st))
Console.WriteLine( "Integer" );
else
Console.WriteLine( "String" );
Console.Write(pt + ": " );
if (IsNumber(pt))
Console.WriteLine( "Integer" );
else
Console.WriteLine( "String" );
}
}
|
Javascript
function isNumber(st) {
for (const c of st) {
if (!Number.isDigit(parseInt(c))) {
return false ;
}
}
return true ;
}
const st = "122B" ;
const pt = "122" ;
console.log(`${st}: `);
if (isNumber(st)) {
console.log( "Integer" );
} else {
console.log( "String" );
}
console.log(`${pt}: `);
if (isNumber(pt)) {
console.log( "Integer" );
} else {
console.log( "String" );
}
|
Python3
def isNumber(st):
return st.isnumeric()
if __name__ = = "__main__" :
st = "122B"
pt = "122"
print (st, end = ': ' )
if isNumber(st):
print ( "Integer" )
else :
print ( "String" )
print (pt, end = ': ' )
if isNumber(pt):
print ( "Integer" )
else :
print ( "String" )
|
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++
#include <iostream>
#include <regex>
#include <string>
using namespace std;
void check( bool result)
{
if (result) {
cout << "Integer" << endl;
}
else {
cout << "String" << endl;
}
}
int main()
{
string s1 = "122B" ;
string s2 = "122" ;
regex pattern( "^-?\\d+$" );
bool result = regex_match(s1, pattern);
cout << s1 << ": " ;
check(result);
result = regex_match(s2, pattern);
cout << s2 << ": " ;
check(result);
return 0;
}
|
Java
public class GFG {
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" ;
boolean result = s1.matches( "^-?\\d+$" );
System.out.print(s1 + ": " );
check(result);
result = s2.matches( "^-?\\d+$" );
System.out.print(s2 + ": " );
check(result);
}
}
|
C#
using System;
using System.Text.RegularExpressions;
class Program {
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" ;
Regex pattern = new Regex( "^-?\\d+$" );
bool result = pattern.IsMatch(s1);
Console.Write(s1 + ": " );
Check(result);
result = pattern.IsMatch(s2);
Console.Write(s2 + ": " );
Check(result);
}
}
|
Javascript
<script>
function check(result) {
if (result) {
document.write( "Integer<br>" );
} else {
document.write( "String<br>" );
}
}
let s1 = "122B" ;
let s2 = "122" ;
let pattern = "^-?\\d+$" ;
let result = Boolean(s1.match(pattern));
document.write(s1 + ": " , end= "" );
check(result);
result = Boolean(s2.match(pattern));
document.write(s2 + ": " , end= "" );
check(result);
</script>
|
Python3
import re
def check(result):
if result:
print ( "Integer" )
else :
print ( "String" )
s1 = "122B"
s2 = "122"
pattern = "^-?\d+$"
result = bool (re.match(pattern, s1))
print (s1 + ": " , end = "")
check(result)
result = bool (re.match(pattern, s2))
print (s2 + ": " , end = "")
check(result)
|
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
public class GFG {
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 + ": " );
check(s1);
System.out.print(s2 + ": " );
check(s2);
}
}
|
Javascript
function check(obj) {
if ( typeof obj === 'number' && Number.isInteger(obj)) {
console.log( "Integer" );
} else if ( typeof obj === 'string' ) {
console.log( "String" );
} else {
console.log( "Other Type" );
}
}
function main() {
var s1 = "122B" ;
var s2 = 122;
console.log(s1 + ": " );
check(s1);
console.log(s2 + ": " );
check(s2);
}
main();
|
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
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);
}
}
|
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:
- 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:
C++
#include <bits/stdc++.h>
using namespace std;
void check( const string& input)
{
try {
size_t pos;
int num = stoi(input, &pos);
if (pos == input.length()) {
cout << "Input is an integer" << endl;
}
else {
cout << "Input is a string" << endl;
}
}
catch (invalid_argument& e) {
cout << "Input is a string" << endl;
}
catch (out_of_range& e) {
cout << "Input is a string" << endl;
}
}
int main()
{
string s1 = "122B" ;
string s2 = "122" ;
cout << s1 << ": " ;
check(s1);
cout << s2 << ": " ;
check(s2);
return 0;
}
|
Java
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);
}
}
|
C#
using System;
class Program
{
static void Check( string input)
{
try
{
int num = int .Parse(input);
if (num.ToString() == input)
{
Console.WriteLine( "Input is an integer" );
}
else
{
Console.WriteLine( "Input is a string" );
}
}
catch (FormatException)
{
Console.WriteLine( "Input is a string" );
}
catch (OverflowException)
{
Console.WriteLine( "Input is a string" );
}
}
static void Main( string [] args)
{
string s1 = "122B" ;
string s2 = "122" ;
Console.Write(s1 + ": " );
Check(s1);
Console.Write(s2 + ": " );
Check(s2);
}
}
|
Javascript
function check(input_str) {
try {
let num = parseInt(input_str);
if (String(num) === input_str) {
console.log( "Input is an integer" );
} else {
console.log( "Input is a string" );
}
} catch (error) {
console.log( "Input is a string" );
}
}
let s1 = "122B" ;
let s2 = "122" ;
process.stdout.write(s1 + ": " );
check(s1);
process.stdout.write(s2 + ": " );
check(s2);
|
Python3
def check(input_str):
try :
num = int (input_str)
if str (num) = = input_str:
print ( "Input is an integer" )
else :
print ( "Input is a string" )
except ValueError:
print ( "Input is a string" )
if __name__ = = "__main__" :
s1 = "122B"
s2 = "122"
print (s1 + ": " , end = "")
check(s1)
print (s2 + ": " , end = "")
check(s2)
|
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:
- 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
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);
}
}
|
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 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.
Last Updated :
11 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...