C++判断wchar_t空白字符

// 引入标准库支持

#include <locale>

#include <codecvt>

#include <string>

#include <vector>

#include <cwctype>

#include <cwchar>

// 标准库提供的判断函数

std::iswblank

源代码:

cpp 复制代码
#include <iostream>
#include <unordered_set>
#include <cwchar>

// 定义所有需检测的Unicode空白字符(按Unicode码点排序)
const std::unordered_set<wchar_t> UNICODE_WHITESPACE_CHARS = {
    // ASCII空白
    L'\t',    // 水平制表符 (U+0009)
    L'\n',    // 换行符 (U+000A)
    L'\v',    // 垂直制表符 (U+000B)
    L'\f',    // 换页符 (U+000C)
    L'\r',    // 回车符 (U+000D)
    L' ',     // 普通空格 (U+0020),

    // 特殊排版空格
    L'\u00A0', // 不换行空格 (U+00A0)
    L'\u2000', // 半角空格 (U+2000)
    L'\u2001', // 全角空格 (U+2001)
    L'\u2002', // 窄空格 (U+2002)
    L'\u2003', // 中等空格 (U+2003)
    L'\u2004', // 三分空格 (U+2004)
    L'\u2005', // 四分空格 (U+2005)
    L'\u2006', // 六分空格 (U+2006)
    L'\u2007', // 数字空格 (U+2007)
    L'\u2008', // 标点空格 (U+2008)
    L'\u2009', // 细空格 (U+2009)
    L'\u200A', // 极细空格 (U+200A),

    // 中文/日文全角空格
    L'\u3000', // 表意空格 (U+3000),

    // 零宽空格
    L'\u200B', // 零宽空格 (U+200B)
    L'\uFEFF', // BOM零宽不换行 (U+FEFF),

    // 数学/特殊空格
    L'\u205F', // 数学空格 (U+205F)
    L'\u1680'  // 欧甘空格 (U+1680)
};

// 判断是否为任何类型的空白字符
bool is_any_whitespace(wchar_t ch) {
    return UNICODE_WHITESPACE_CHARS.count(ch) > 0;
}

// 扩展:判断字符串是否全为空白字符
bool is_whitespace_string(const std::wstring& str) {
    for (wchar_t ch : str) {
        if (!is_any_whitespace(ch)) return false;
    }
    return !str.empty();
}

int main() {
    // 测试用例
    struct TestCase {
        std::wstring input;
        bool expected;
    };

    TestCase tests[] = {
        {L"Hello World", false},
        {L"\t\n  \u3000", true},
        {L"\u200B", true},
        {L"\uFEFF", true},
        {L"\u205F", true},
        {L"\u00A0", true},
        {L"A", false},
        {L"\u4E00", false}  // 中文字符
    };

    for (const auto& test : tests) {
        std::wcout << L"输入: '" << test.input << L"' -> "
                  << (is_any_whitespace(test.input[0]) ? L"空白" : L"非空白") << L"\n";
    }

    return 0;
}
相关推荐
袁袁袁袁满7 分钟前
Python使用uuid生成唯一密钥uid详细教程
开发语言·python·uuid·唯一密钥uid
Logan Lie7 分钟前
Go 反射(Reflection)详解:从入门到实践
开发语言·后端·golang
爱装代码的小瓶子9 分钟前
【c++进阶】c++11下类的新变化以及Lambda函数和封装器
java·开发语言·c++
m0_7482500314 分钟前
C++ 标准库概述
开发语言·c++
FAFU_kyp15 分钟前
Rust 所有权(Ownership)学习
开发语言·学习·rust
superman超哥21 分钟前
Rust 异步性能的黑盒与透视:Tokio 监控与调优实战
开发语言·后端·rust·编程语言·rust异步性能·rust黑盒与透视·tokio监控与调优
lkbhua莱克瓦2425 分钟前
进阶-存储对象2-存储过程上
java·开发语言·数据库·sql·mysql
Mr -老鬼32 分钟前
Rust 知识图谱 -进阶部分
开发语言·后端·rust
LawrenceLan34 分钟前
Flutter 零基础入门(十三):late 关键字与延迟初始化
开发语言·前端·flutter·dart