日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

c语言字符串不能是数字,C语言判断字符串是否为数字

發布時間:2023/12/31 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c语言字符串不能是数字,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'))

/* Whether string s is a number.

Returns 0 for non-number, 1 for integer, 2 for hex-integer, 3 for float */

int is_number(char * s)

{

int base = 10;

char *ptr;

int type = 0;

if (s==NULL) return 0;

ptr = s;

/* skip blank */

while (IS_BLANK(*ptr)) {

ptr++;

}

/* skip sign */

if (*ptr == '-' || *ptr == '+') {

ptr++;

}

/* first char should be digit or dot*/

if (IS_DIGIT(*ptr) || ptr[0]=='.') {

if (ptr[0]!='.') {

/* handle hex numbers */

if (ptr[0] == '0' && ptr[1] && (ptr[1] == 'x' || ptr[1] == 'X')) {

type = 2;

base = 16;

ptr += 2;

}

/* Skip any leading 0s */

while (*ptr == '0') {

ptr++;

}

/* Skip digit */

while (IS_DIGIT(*ptr) || (base == 16 && IS_HEX_DIGIT(*ptr))) {

ptr++;

}

}

/* Handle dot */

if (base == 10 && *ptr && ptr[0]=='.') {

type = 3;

ptr++;

}

/* Skip digit */

while (type==3 && base == 10 && IS_DIGIT(*ptr)) {

ptr++;

}

/* if end with 0, it is number */

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语言字符串不能是数字,C语言判断字符串是否为数字的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。