C++ isspace()

isspace() 函数原型

int isspace(int ch);

isspace() 函数根据当前的 C 区域设置,检查 ch 是否是空白字符。默认情况下,以下字符是空白字符:

  • 空格 (0x20, ' ')
  • 换页符 (0x0c, '\f')
  • 换行符 (0x0a, '\n')
  • 回车符 (0x0d, '\r')
  • 水平制表符 (0x09, '\t')
  • 垂直制表符 (0x0b, '\v')

如果 ch 的值不能表示为 unsigned char 或不等于 EOF,则 isspace() 的行为是未定义的。

它定义在 <cctype> 头文件中。

isspace() 参数

ch: 要检查的字符。

isspace() 返回值

如果 ch 是空白字符,isspace() 函数返回非零值,否则返回零。

示例:isspace() 函数如何工作

#include <cctype>
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char str[] = "<html>\n<head>\n\t<title>C++</title>\n</head>\n</html>";

    cout << "Before removing whitespace characters" << endl;
    cout << str << endl << endl;

    cout << "After removing whitespace characters" << endl;
    for (int i=0; i<strlen(str); i++)
    {
        if (!isspace(str[i]))
            cout << str[i];
    }
    
    return 0;
}

运行程序后,输出将是

Before removing whitespace characters
<html>
<head>
	<title>C++</title>
<head>
<html>

After removing whitespace characters
<html><head><title>C++</title></head></html>
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战