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>