C++ isspace() 判断字符是否为空格
isspace() 原型
int isspace(int ch);
isspace()
函数用于检查 ch
是否为空白字符,这是根据当前 C 语言区域设置分类的。默认情况下,以下字符被视为空白字符:
- 空格 (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 << "移除空白字符前" << endl;
cout << str << endl << endl;
cout << "移除空白字符后" << endl;
for (int i=0; i<strlen(str); i++)
{
if (!isspace(str[i]))
cout << str[i];
}
return 0;
}
当你运行程序时,输出将是:
移除空白字符前
<html>
<head>
<title>C++</title>
</head>
</html>
移除空白字符后
<html><head><title>C++</title></head></html>