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.
Update (2015-02-10):
The signature of the C++
function had been updated. If you still see your function signature accepts a
const char *
argument, please click the reload button
to reset your code definition.
enum numtype {
NOTNUM = 0,
INTNUM,
POINUM,
};
enum numtype checknum(char *numstr)
{
int len, i, ret = INTNUM;
if (*numstr == '-' || *numstr == '+')
numstr++;
len = strlen(numstr);
if (!len)
return NOTNUM;
for (i = 0; i < len; i++) {
if (!isdigit(numstr[i]) && numstr[i] != '.')
return NOTNUM;
if (numstr[i] == '.') {
if (ret == POINUM || !i && !isdigit(numstr[i + 1]))
return NOTNUM;
else
ret = POINUM;
}
}
return ret;
}
bool isNumber(char* s)
{
int slen = strlen(s);
char *end = s + slen - 1;
char *begin = s;
while (end - s > 0 && *end == ' ')
*end-- = '\0';
while (*begin == ' ')
*begin++ = '\0';
if (!*begin)
return 0;
s = begin;
char *ep = strchr(s, 'e');
if (!ep)
return checknum(s) == NOTNUM ? 0 : 1;
*ep = '\0';
if (checknum(s) != NOTNUM && checknum(ep + 1) == INTNUM)
return 1;
return 0;
}
test data
12.12
-13.23
12.12e8
12.12e8.1
-13.23e-8
.1 (true)
3. (true)
.
0