使用C语言isspace函数的各种方法

223 阅读2分钟

定义在ctype.h头文件中,C语言的isspace函数测试空白字符。

基本用法

isspace函数的语法如下。

int isspace(int arg);

isspace函数接受字符值并检查它是否是一个公认的C语言空白字符。

如果该字符是一个空白字符,则该函数返回一个非零值,否则返回零。

C isspace函数实例

下面是isspace函数使用的一个简单例子。

例1

#include <stdio.h>

#include <ctype.h>


int main() {

    int i = '\n';

    int whitspace;

    whitspace = isspace(i);

    if (whitspace == 0) {

        printf("That is not a whitespace character");

    }

    else {

        printf("Definately Whitespace character");

    }

    return 0;

}

由于 \n 是一个有效的空白字符,isspace 函数的返回值是非零的。

例2

我们还可以使用十六进制值来检查所发现的特定类型的空白字符。例如,下面实现了一个开关语句来检查各种空白字符。

#include <stdio.h>

#include <ctype.h>

int main() {

    char c = ' ';

    switch(c) {

        case 0x20:

            printf("space!\n");

            break;

        case 0x09:

            printf("horizontal tab!\n");

            break;

        case 0x0a:

            printf("newline!\n");

            break;

        case 0x0b:

            printf("vertical tab!\n");

            break;

        case 0x0c:

            printf("feed!\n");

            break;

        case 0x0d:

            printf("carriage return!\n");

            break;

        default:

            printf("Done\n");

    }

    return 0;

}

一个例子的输出如图所示。

gcc -g isspace.c

./a.out

space!

例3

isspace函数的另一个实现例子是确定一个给定字符串中的空格数。

下面的示例代码显示了如何实现这样的逻辑。

#include <stdio.h>

#include <ctype.h>

int main() {

    char c;

    int i = 0;

    int count = 0;

    char str[] = "This is C programming language!";

    while (str[i] != '\0') {

        c = str[i];

        if (isspace(c)){

            count++;

        }

        i++;

    }

    printf("Whitespaces: %d \n", count);

    return 0;

}

在上面的例子中,我们首先定义了一个char类型来存储字符串中的各个字符。我们用这个字符来检查它是否是一个空白值。

接下来,我们定义了一个int i,用来迭代字符串中的字符序列。

我们还定义了一个count值,用来存储在字符串中发现的空白处的数量,只要该字符不是空结尾字符。

一个例子的输出是这样的。

gcc -g isspace.c

./a.out

Whitespaces: 4

有效的空白字符

以下是有效的C语言空白字符

空白字符说明
' '空格
\t横向标签
\n换行
\v垂直制表符
\f换行
\r回车

总结

这是一个快速教程,介绍了使用C语言isspace函数的各种方法。