C语言 判断字符串是否为数字字符串

1. 方法一:使用C 库函数 - isdigit()

       头文件包含:#include <ctype.h>

       函数描述:C 库函数 int isdigit(int c) 检查所传的字符是否是十进制数字字符。十进制数字是:0 1 2 3 4 5 6 7 8 9。

       如果 c 是一个数字,则该函数返回非零值,否则返回 0。

2. 方法二:使用C 库函数 - strspn()

      头文件包含:#include <string.h>

       函数描述:C 库函数 size_t strspn(const char *str1, const char *str2) 检索字符串 str1 中第一个不在字符串 str2 中出现的字符下标。

  • str1 -- 要被检索的 C 字符串。
  • str2 -- 该字符串包含了要在 str1 中进行匹配的字符列表。
  • 该函数返回 str1 中第一个不在字符串 str2 中出现的字符下标。

 测试:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <Windows.h>


void main(void)
{
    char str[] = "123abc";
    char str2[] = "456";
    int i;
    printf("\r\n-----------方法一--------------\r\n");
    for(i = 0; str[i] != 0; i++)
        if(isdigit(str[i]))
            printf("%c is an digit character\r\n", str[i]);
        else
            printf("%c is not an digit character\r\n", str[i]);

    printf("\r\n-----------方法二--------------\r\n");
    if (strspn(str, "0123456789") == strlen(str))
    {
        printf("str:%s 全数字\r\n",str);
    }
    else
    {
        printf("str:%s 不全是数字\r\n",str);
    }

    if (strspn(str2, "0123456789") == strlen(str2))
    {
        printf("str2:%s 全数字\r\n",str2);
    }
    else
    {
        printf("str2:%s 不全是数字\r\n",str2);
    }
}

测试结果:

-----------方法一--------------
1 is an digit character
2 is an digit character
3 is an digit character
a is not an digit character
b is not an digit character
c is not an digit character

-----------方法二--------------
str:123abc 不全是数字
str2:456 全数字
PS E:\Projects\CProjects\test>

  • 8
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值