找回密码
 register

QQ登录

只需一步,快速开始

查看: 11|回复: 0

[C++] isspace 判断字符是否为空白字符

[复制链接]

[C++] isspace 判断字符是否为空白字符

[复制链接]
  • 打卡等级:热心大叔
  • 打卡总天数:240
  • 打卡月天数:17
  • 打卡总奖励:238
  • 最近打卡:2025-07-19 00:57:06
Waylee

主题

0

回帖

2万

积分

仙帝

积分
26258
Waylee 2025-7-18 17:48 | 显示全部楼层 |阅读模式 | Google Chrome | Windows 10

马上注册,查看网站隐藏内容!!

您需要 登录 才可以下载或查看,没有账号?register

×
#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;
}
您需要登录后才可以回帖 登录 | register

本版积分规则

雪舞知识库 | 浙ICP备15015590号-1 | 萌ICP备20232229号|浙公网安备33048102000118号 |网站地图|天天打卡

GMT+8, 2025-7-19 06:27 , Processed in 0.109459 second(s), 5 queries , Redis On.

Powered by XueWu Licensed

Copyright © Tencent Cloud.

快速回复 返回顶部 返回列表