#include <cctype> // 或 #include <ctype.h>
#include <iostream>
int main()
{
char ch = '\0';
if (isspace(ch)) {
std::cout << "空白字符!\n";
}
else {
std::cout << "非空白字符!\n";
}
return 0;
}
isspace 判断的字符范围:
isspace 会返回 true 的字符包括:
-
空格 ' '
-
换行符 '\n'
-
制表符 '\t'
-
回车符 '\r'
-
垂直制表符 '\v'
-
换页符 '\f'
注意事项:
参数应是 unsigned char 类型或者 EOF。不要直接传入负值的 char(除非你确定它是 ASCII),否则可能导致未定义行为。
如果用在 char 上,可以这样安全处理:
isspace(static_cast<unsigned char>(c))
案例:统计字符串中的空白字符数量
#include <cctype>
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello \t World\nThis is C++";
int count = 0;
for (char c : str) {
if (std::isspace(c)) {
count++;
}
}
std::cout << "空白字符数量: " << count << std::endl;
return 0;
}
|