Validate if a given string is numeric.
Some examples:
“0”=>true
" 0.1 "=>true
“abc”=>false
“1 a”=>false
“2e10”=>true
Note: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one.
class Solution {
public:
bool isNumber(const char *s)
{
if (NULL == s)
return false;
string str (s);
regex r(" *[-+]?(?:\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)? *");
return regex_match(str,r);
}
};
测试
#include<iostream>
#include <regex>
using namespace std;
class Solution {
public:
bool isNumber(const char *s)
{
if (NULL == s)
return false;
string str (s);
regex r(" *[-+]?(?:\\d+\\.?|\\.\\d+)\\d*(e[-+]?\\d+)? *");
return regex_match(str,r);
}
};
int main()
{
Solution s;
const char * S = ".155e12";
if (s.isNumber(S))
cout<<"true";
else
cout<<"false";
}