Validate if a given string is numeric.
"0" => true " 0.1 " => true "abc" => false "1 a" => false "2e10" => true
The problem can be solved in 3 methods:
- Deterministic Finite Automaton
- Regex
- 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:
- Skip leading spaces.
- Skip sign.
- Integer, decimal point and fractional parts. Ensure it in between {+, -, ., e, [0-9]}
- Exponential bit. Check that no ‘.’ comes after ‘e’.
- Skip following spaces.
- Chek if you have reached to the end.
So we check it programmatically as below:
Solution in C++
#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"; //Additional test cases //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