C Primer Plus 第11章 11.7 ctype.h字符函数和字符串

て烟熏妆下的殇ゞ 提交于 2019-11-27 04:43:00

第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)。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!