• C Primer Plus(6) 中文版 第11章 字符串和字符串函数 11.7 ctype.h字符函数和字符串


    11.7 ctype.h字符函数和字符串
    ctype.h中有关于处理字符的函数原型。
    /* mod_str.c -- modifies a string */
    #include
    #include
    #include
    #define LIMIT 81
    void ToUpper(char *);
    int PunctCount(const char *);

    int main(void)
    {
        char line[LIMIT];
        char * find;
        
        puts("Please enter a line:");
        fgets(line, LIMIT, stdin);
        find = strchr(line, '\n');   // look for newline
        if (find)                    // if the address is not NULL,
            *find = '\0';            // place a null character there
        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;

    /* 输出:

    */ 

    根据ANSI C中的定义,toupper()函数只改变小写字符。但是一些很旧的C实现不会自动检查大小写,所以以前的代码通常会这样写:
    if( islower( *str ) ) /*ANSI C之前的做法--在转换大小写之前先检查*/
        *str = toupper( *str );
    顺带一提,ctype.h中的函数通常作为宏(macro)来实现。这些C预处理器宏的作用很像函数,但是两者有一些重要的区别。
    该程序使用fgets()和strchr()组合,读取一行输入并把换行符替换成空字符。这种方法与使用s_gets()的区别是:s_gets()会处理输入行剩余字符(如果有的话),为下一次输入做好准备。而本例只有一条输入语句,就没必要进行多余的步骤。

  • 相关阅读:
    Python下载与安装进阶
    机器学习之决策树、随机森林
    STM32学习笔记:驱动SPI外设读写FLASH
    OpenCV视频防抖技术解析
    Unity开发者必备的C#脚本技巧
    第一天-基本知识整理,目的:能写点东西
    JavaEE-文件IO操作
    React中ref的使用方法和使用场景(详解)
    小程序之微信登录授权(6)
    轮播图(多个一起轮播)
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/126283164