1. isalpha() -- 测试字符是否英文字母
原型:int isalpha(int ch)
用法:头文件加入#include <cctype>(C语言使用<ctype.h>)
功能:判断字符ch是否为英文字母,当ch为英文字母a-z或A-Z时,在标准c中相当于使用“isupper(ch)||islower(ch)”做测试,返回非零值(不一定是1),否则返回零。
例子:
#include<ctype.h>
#include<stdio.h>
int main(void)
{
char ch;
int total = 0;
/* calculate letter number */
do
{
ch=getchar();
if(isalpha(ch)!=0)
total++;
}while(ch!='.');/*end with "."*/
printf("The total of letters is %d \n",total);
return 0;
}
运行结果:
$ ./a.out
hello, how
.
The total of letters is 8
2. isupper() ---测试字符是否大写英文字母
原型:extern int isupper(int c);
头文件:<cctype>(旧版本的编译器使用<ctype.h>)
功能:判断字符c是否为大写英文字母
说明:当参数c为大写英文字母(A-Z)时,返回非零值,否则返回零。
附加说明: 此为宏定义,非真正函数。
例子:#include <ctype.h>
#include <stdio.h>
int main()
{
char Test[]="a1B2c3D4";
char *pos;
pos=Test;
while(*pos!=0) {
if(isupper(*pos))
printf("%c",*pos);
pos++;
}
printf("\n");
return 0;
}
运行结果:
$ ./a.out
BD例2:
#include <stdio.h>
#include <ctype.h>
main()
{
int c;
c='a';
printf("%c:%s\n",c,isupper(c)?"yes":"no");
c='A';
printf("%c:%s\n",c,isupper(c)?"yes":"no");
c='7';
printf("%c:%s\n",c,isupper(c)?"yes":"no");
return 0;
}运行结果:
$ ./a.out
a:no
A:yes
7:no
3. islower() --- 测试字符是否为小写字母
头文件: #include<cctype>(旧版本的编译器使用<ctype.h>)
定义函数 :int islower(int c)
函数说明 : 检查参数c是否为小写英文字母。
返回值: 若参数c为小写英文字母,则返回TRUE,否则返回NULL(0)。
附加说明:此为宏定义,非真正函数。
例子:#include <ctype.h>
#include <stdio.h>
int main()
{
char str[]="123@#FDsP[e?";
int i;
for(i=0;str[i]!=0;i++)
if(islower(str[i]))
printf("%c is a lower-case character\n",str[i]);
return 0;
}运行结果:
$ ./a.out
s is a lower-case character
e is a lower-case character
4. isdigit() --- 测试字符是否为数字
原型:extern int isdigit(char c);
用法:#include <ctype.h>
功能:判断字符c是否为数字
说明:当c为数字0-9时,返回非零值,否则返回零。
附加说明 此为宏定义,非真正函数。 例子:
#include <stdio.h>
#include <ctype.h>
int main()
{
int c;
c='a';
printf("%c:%s\n",c,isdigit(c)?"yes":"no");
c='9';
printf("%c:%s\n",c,isdigit(c)?"yes":"no");
c='*';
printf("%c:%s\n",c,isdigit(c)?"yes":"no");
return 0;
}
运行结果:
$ ./a.out
a:no
9:yes
*:no
C语言字符测试函数
本文介绍了C语言中用于测试字符属性的基本函数,包括isalpha(), isupper(), islower(), 和isdigit()。通过这些函数可以轻松地判断字符是否为字母、是否为大写字母、是否为小写字母以及是否为数字。
2016

被折叠的 条评论
为什么被折叠?



