6. 字符分类和转换(ctype.h)

C 语言标准库中提供了 字符分类与处理 的一些函数。包括英文字符的大小写判断,大小写转换等函数。

头文件

ctype.h

进程相关的函数

函数
说明
字符分类
以下函数分类成功返回非零值,失败返回 0。
int isalnum(int c);
是否为字母或数字
int isalpha(int c);
是否为字母
int iscntrl(int c);
是否为控制字符
int isdigit(int c);
是否为十进制数字
int isgraph(int c);
是否为图形字符(除空格外的可打印字符)
int islower(int c);
是否为小写字母
int isprint(int c);
是否为可打印字符
int ispunct(int c);
是否为标点符号
int isspace(int c);
是否为空白字符(空格、\t\n\f\r\v
int isupper(int c);
是否为大写字母
int isxdigit(int c);
是否为十六进制数字
int isascii(int c);
是否为 ascii 字符(值在0-127之间)
int isblank(int c);
是否为空格或制表符\t
字符转换函数
int toupper(int c);
转换为大写
int tolower(int c);
转换为小写

示例:

写函数 to_upper_str,将字符串中的小写字符转成大写字符显示。

// filename: myctype.c
#include <stdio.h>
#include <ctype.h>

// 将字符串中的英文转为大写字符
void to_upper_str(char * str) {
    while (*str) {
        if (islower(*str))
            *str = toupper(*str);
        str++;
    }
}

int main(int argc, char * argv[]) {
    char buf[100] = "hElLo worLd!";

    to_upper_str(buf);

    printf("%s\n", buf);

    return 0;
}

编译和运行结果如下:

weimingze@mzstudio:~$ gcc -o myctype myctype.c
weimingze@mzstudio:~$ ./myctype
HELLO WORLD!

练习

写函数 stat_word_count 给出一段英文文章,返回英文文章中英文单词的个数,部分程序内容如下:

#include <stdio.h>
#include <ctype.h>

int stat_word_count(const char * str) {
    // ...
}

int main(int argc, char * argv[]) {
    char buf[100] = "hello world! \nhello china!\n";

    printf("%d\n", stat_word_count(buf));  // 打印 4
    return 0;
}