首页 > 编程笔记 > C语言函数大全

C语言isspace():判断一个字符是否为空白符

isspace() 是 C 语言的标准库函数,定义在头文件<ctype.h>中。

isspace() 函数用于检查给定的字符是否为空白字符。所谓空白字符,包括:空格 ' '、制表符 '\t'、换行符 '\n'、垂直制表符 '\v'、换页符 '\f' 和回车符 '\r'。

isspace() 函数的原型如下:

int isspace(int c);

参数

c 表示要检查的字符。虽然参数是 int 类型,但通常传入的是 char 类型的字符。

返回值

如果传入的字符是空白字符,则返回非零值;如果传入的字符不是空白字符,则返回零。

【实例】用 isspace() 函数来检查一个字符串中的每个字符是否为空白字符,请看下面的 C语言代码。
#include <stdio.h>
#include <ctype.h>

int main() {
    char str[] = "Hello\tWorld\n! ";

    for(int i = 0; str[i] != '\0'; i++) {
        if(isspace(str[i])) {
            printf("Character at index %d is a whitespace character.\n", i);
        } else {
            printf("Character at index %d is NOT a whitespace character.\n", i);
        }
    }

    return 0;
}
输出结果为:

Character at index 0 is NOT a whitespace character.
Character at index 1 is NOT a whitespace character.
Character at index 2 is NOT a whitespace character.
Character at index 3 is NOT a whitespace character.
Character at index 4 is NOT a whitespace character.
Character at index 5 is a whitespace character.
Character at index 6 is NOT a whitespace character.
Character at index 7 is NOT a whitespace character.
Character at index 8 is NOT a whitespace character.
Character at index 9 is NOT a whitespace character.
Character at index 10 is NOT a whitespace character.
Character at index 11 is a whitespace character.
Character at index 12 is NOT a whitespace character.
Character at index 13 is a whitespace character.

示例中使用 isspace() 函数检查每个字符是否是空白字符,其中制表符 '\t'、换行符 '\n' 和空格 ' ' 都被正确地识别为空白字符。

相关文章