C语言isalnum():判断一个字符是否为字母或者数字
<ctype.h>
头文件中,用于检查传入的字符是否是字母('A'~'Z' 和 'a'~'z')或数字(0~9)。isalnum() 函数的原型如下:
int isalnum(int c);
参数
c 是要检查的字符。虽然参数是 int 类型,但通常传入的是 char 类型的字符,传入 EOF 也是有效的。返回值
如果传入的字符是字母或数字,函数返回非零值;如果传入的字符不是字母或数字,函数返回零。【实例一】使用 isalnum() 函数判断输入的字符是否是字母或数字。
#include <stdio.h> #include <ctype.h> int main() { char ch; printf("input a character:"); /*输入一个字符*/ scanf("%c", &ch); if (isalnum(ch)) { /*判断输入字符是否是字母或数字字符*/ printf("%c is alnum.", ch); } else { printf("%c is not alnmu.", ch); } }运行结果:
input a character:.
. is not alnmu.
【实例二】使用 isalnum() 函数检查一个字符串中的每个字符是否为字母或数字,请看下面的C语言代码。
#include <stdio.h> #include <ctype.h> int main() { char str[] = "C0ding is fun!"; for(int i = 0; str[i] != '\0'; i++) { if(isalnum(str[i])) { printf("'%c' is an alphanumeric character.\n", str[i]); } else { printf("'%c' is NOT an alphanumeric character.\n", str[i]); } } return 0; }运行结果:
'C' is an alphanumeric character.
'0' is an alphanumeric character.
'd' is an alphanumeric character.
'i' is an alphanumeric character.
'n' is an alphanumeric character.
'g' is an alphanumeric character.
' ' is NOT an alphanumeric character.
'i' is an alphanumeric character.
's' is an alphanumeric character.
' ' is NOT an alphanumeric character.
'f' is an alphanumeric character.
'u' is an alphanumeric character.
'n' is an alphanumeric character.
'!' is NOT an alphanumeric character.