第7章“C控制语句 分支和跳转”介绍了ctype.h系列字符相关的函数。这些函数不能被 应用于整个字符串,可是能够被应用于字符串中的个别字符。程序清单11.26定义了一个函数,它把toupper( )函数应用于一个字符串中的每一个字符,这样就能够把整个字符串转换成大写。此外,程序还定义了一个使用isputct( )函数计算一个字符串中的标点字符个数的函数。函数
程序清单11.26 mod_str.c程序编码
/*mod_str.c 修改一个字符串*/ #include <stdio.h> #include <string.h> #include <ctype.h> #define LIMIT 80 void ToUpper(char *); int PunctCount(const char *); int main(void) { char line[LIMIT]; puts("Please enter a line: "); gets(line); ToUpper(line); puts(line); printf("That line has %d punctuation characters.\n",PunctCount(line)); return 0; } void ToUpper(char * str) { while(*str) { *str=toupper(*str); str++; } } int PunctCount(const char *str) { int ct=0; while(*str) { if(ispunct(*str)) ct++; str++; } return ct; } 下面是输出: Please enter a line: Me? You talkin' to me? Get outta here! ME? YOU TALKIN' TO ME? GET OUTTA HERE! That line has 4 punctuation characters.
循环while(*str)处理str指向的字符串的每一个字符,直到碰见空字符。当遇到空字符时,*str的值为0(空字符的编码),即为假,则循环结束。code
顺便提一下,cype.h函数一般被做为宏来实现。这些C预处理器指令的做用很像函数,可是有一些重要差异。在第16章 C预处理器和C库 中咱们会介绍宏。字符串
接下来,咱们讨论main()函数圆括号中的void(11.8)。get