bcpkh wrote:
Hello All
I need to check a string to make sure it does not contain any non
numeric characters, the problem that I face is that the string is
fairly long, 2784601121574585949, strtol etc. can't process this
because much bigger than long obviously.
Is there a way to check this string without resorting to scanning
through the entire string a character at a time?
Any method you use will involve scanning through the string. That can be
done as part of the operation of a standard library function, or you can
do it manually with a loop construct. It probably won't make much
difference either way.
Any suggestions would be much appreciated.
This solution uses standard library functions to avoid explicitly coding
a loop. It is not the most efficient solution, since it does scan
through the string twice, once for strspn and once for strlen.
#include <string.h>
#include <stdio.h>
....
const char *str = "2784601121574585949";
const char *digits = "0123456789";
size_t digit_length = strspn(str, digits);
size_t str_length = strlen(str);
if(digit_length == str_length)
{
printf("only digits\n");
}
else
{
printf("non-digit character at %d\n", (int)digit_length);
}
Here's an alternative with a loop. It's more concise and elegant, and
only scans the string once. Notice the empty loop body. The entire
purpose of the loop is to advance the pointer p to a particular
location, the first non-digit location. If the string is all digits,
then that location will be the null character at the end of the string.
There's no need to explicitly test for the end of the string in the loop
condition, since isdigit(0) will return 0.
#include <ctype.h>
#include <stdio.h>
....
const char *str = "2784601121574585949";
const char *digits = "0123456789";
const char *p;
for(p = str; isdigit(*p); p++);
if(*p == '\0')
{
printf("only digits\n);
}
else
{
printf("non-digit character at %d\n", (int)(p - str));
}
--
Simon.