第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(空字符的编码),即为假,则循环结束。
顺便提一下,cype.h函数通常被作为宏来实现。这些C预处理器指令的作用很像函数,但是有一些重要差别。在第16章 C预处理器和C库 中我们会介绍宏。
接下来,我们讨论main()函数圆括号中的void(11.8)。
来源:oschina
链接:https://my.oschina.net/u/2754880/blog/738599