C语言标准库―#include
2014/11/25 by jxlijunhao 在这个头文件中包含了对字符测试的函数,如检查一个字符串中某一个字符是否为数字,或者字母等,还包含了字符映射函数,如将大写字母映射成小写字母等。下面是通过查阅标准手册,记录的一些函数的用法,方便以后查找之用。
1,isalpha, 判读是否为字母 isdigit, 判读是否为数字
#include
#include
int main() { int i=0; char str[]="c++11"; while (str[i]) { if (isalpha(str[i])) printf("character %c is alpha\n",str[i]); else if (isdigit(str[i])) printf("character %c is digit\n",str[i]); else printf("character %c is not alpha or digit\n",str[i]); i++; } }
输出结果为:
character c is alpha
character + is not alpha
character + is not alpha
character 1 is digit
character 1 is digit
isxdigit :判断是否为 A~F, a~f
2,isalnum: 是字母或者数字
#include
#include
int main() { int i=0; int count=0; char str[]="c++11"; //统计一个字符串中是字母或者数字的个数 while (str[i]) { if (isalnum(str[i])) count++; i++; } printf("there are %d alpha or digit is %s",count,str); return 0; }
输出结果:
3
3,islower, 是否为小写, isupper, 是否为大写 tolower, 转化为小写 touuper 转化为大写
#include
#include
int main() { char str[]="I love ShangHai"; //将字符串中的小写字母转化为大写字母 int i=0; char c; while (str[i]) { c=str[i]; if (islower(c))str[i]=toupper(c); i++; } printf("%s\n",str); }
I LOVE SHANGHAI
4, isspace: 判断一个字符是否为空格
#include
#include
int main () { char c; int i=0; char str[]="Example sentence to test isspace\n"; while (str[i]) { c=str[i]; if (isspace(c)) c='\n'; putchar (c); i++; } return 0;
输出为:
Example
sentence
to
test
isspace
一个应用:将一个包含0~9,A~F的字符串(十六进制)转化成整型:
#include
#include
#include
long atox(char *s) { char xdigs[]="0123456789ABCDEF"; long sum; while (isspace(*s))++s; for (sum=0L;isxdigit(*s);++s) { int digit=strchr(xdigs,toupper(*s))-xdigs; //地址相减 sum=sum*16+digit; } return sum; } int main () { char *str="21"; long l=atox(str); printf("%d\n",l); return 0; }
函数strchr ,是包含中
中的一个函数,其原型为
const char * strchr ( const char * str, int character );
返回的是要查找的字符在字符串中第一次出现的位置,返回值是指向该字符的指针