标簽:c
判斷一個字元串是否為數字, 聽起來很簡單,實作還是有點難度的。 最近寫了一個,如下:
#define IS_BLANK(c) ((c) == ' ' || (c) == '\t')
#define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
#define IS_ALPHA(c) ( ((c) >= 'a' && (c) <= 'z') || ((c) >= 'A' && (c) <= 'Z') )
#define IS_HEX_DIGIT(c) (((c) >= 'A' && (c) <= 'F') || ((c) >= 'a' && (c) <= 'f'))
int is_number(char * s)
{
int base = 10;
char *ptr;
int type = 0;
if (s==NULL) return 0;
ptr = s;
while (IS_BLANK(*ptr)) {
ptr++;
}
if (*ptr == '-' || *ptr == '+') {
ptr++;
}
if (IS_DIGIT(*ptr) || ptr[0]=='.') {
if (ptr[0]!='.') {
if (ptr[0] == '0' && ptr[1] && (ptr[1] == 'x' || ptr[1] == 'X')) {
type = 2;
base = 16;
ptr += 2;
}
while (*ptr == '0') {
ptr++;
}
while (IS_DIGIT(*ptr) || (base == 16 && IS_HEX_DIGIT(*ptr))) {
ptr++;
}
}
if (base == 10 && *ptr && ptr[0]=='.') {
type = 3;
ptr++;
}
while (type==3 && base == 10 && IS_DIGIT(*ptr)) {
ptr++;
}
if (*ptr==0)
return (type>0) ? type : 1;
else
type = 0;
}
return type;
}
is_number(char *) 函數判斷字元串是否為數字。如果不是,傳回0。如果是整數,傳回1。如果是十六進制整數,傳回2. 如果是小數,傳回3.
編一個測試程式:
#include
#include
int main(int argc, char**argv)
{
assert( is_number(NULL) ==0 );
assert( is_number("") ==0 );
assert( is_number("9a") ==0 );
assert( is_number("908") ==1 );
assert( is_number("-908") ==1 );
assert( is_number("+09") ==1 );
assert( is_number("-+9") ==0 );
assert( is_number(" 007") ==1 );
assert( is_number("0x9a8F") ==2 );
assert( is_number("-0xAB") ==2 );
assert( is_number("-9.380") ==3 );
assert( is_number("-0xFF.3") ==0 );
printf("test OK\n");
}
運作, "test OK"
标簽:c
原文:http://blog.csdn.net/c80486/article/details/45066439