Validate if a given string is numeric.
Some examples:
“0” => true
” 0.1 ” => true
“abc” => false
“1 a” => false
“2e10” => true
Below is the list of characters that can be in a valid decimal number:
• Numbers 0-9
• Exponent – “e”
• Positive/negative sign – “+”/”-”
• Decimal point – “.”
The problem can be solved in 3 methods:
1. Deterministic Finite Automaton
2. Regex
3. Simple Method
We are going to look at 3rd method. If anybody is able to solve by 1st and 2nd method, please leave the solution in the comment section of this post.
So to check if the given string is a number, we need to check the following cases:
1. Skip leading spaces.
2. Skip sign.
3. Integer, decimal point and fractional parts. Ensure it is {+, -, ., e, [0-9]}
4. Exponential bit. Check that no ‘.’ comes after ‘e’.
5. Skip following spaces.
6. Make sure that’s the end.
So we check it programmatically as below:
/*
* File : check_if_the_number_is_valid.cpp
*/
#include<iostream>
#include<string>
using namespace std;
bool isNumber(string s)
{
int n = s.size();
if(n == 0) return false;
int i = 0;
//Skip leading spaces.
while(s[i] == ' ') i++;
//Significand
if(s[i] == '+' || s[i] == '-') i++;
int cnt = 0;
//Integer part
while(isdigit(s[i]))
{
i++;
cnt++;
}
//Decimal point
if(s[i] == '.') i++;
//Fractional part
while(isdigit(s[i]))
{
i++;
cnt++;
}
if(cnt == 0) return false; //No number in front or behind '.'
//Exponential
if(s[i] == 'e')
{
i++;
if(s[i] == '+' || s[i] == '-') i++;
if(!isdigit(s[i])) return false; //No number follows
while(isdigit(s[i])) i++;
}
//Skip following spaces;
while(s[i] == ' ') i++;
return s[i] == '\0';
}
int main()
{
string str = "2e10";
//Other test case
//string str = "abc";
//string str = " 6e-1";
//string str = " 99e2.5 ";
if (isNumber(str))
cout<<"The string is a valid number"<< endl;
else
cout<<"The string is not a valid number"<< endl;
}
Output:
The string is a valid number