C++ 字符串 - 如何为 wstring 实现这个 'IsEmptyOrSpace(string)' 方法?

标签 c++ string encoding

好的,我在 StackOverflow 上搜索了如何检查字符串是否为空或只有空格。但是,它只适用于 ANSI 字符串。我怎样才能让它与 wstring 一起工作? ?

代码如下:

#include <string>
using namespace std;

//! Checks if a string is empty or is whitespace.
bool IsEmptyOrSpace(const string& str) {
    string::const_iterator it = str.begin();

    do {
        if (it == str.end())
            return true;
    } while (*it >= 0 && *it <= 0x7f && isspace(*(it++)));
    // One of these conditions will be optimized away by the compiler.
    // Which one depends on whether the characters are signed or not.

    return false;
}

我的第一个想法是改变isspace(*(it++))iswspace(*(it++)) , 但之前的两个条件只适用于 ASCII,对吧?到目前为止,这是我尝试使函数适应 wstring 的过程。的:

bool IsEmptyOrSpaceW(const wstring& str) {
    String::const_iterator it = str.begin();

    do {
        if (it == str.end())
            return true;
    } while (*it >= 0 && *it <= 0x7f && iswspace(*(it++)));
    // One of these conditions will be optimized away by the compiler.
    // Which one depends on whether the characters are signed or not.

        // Do I need to change "*it >= 0 && *it <= 0x7f" to something else?

    return false;
}

我的方法接近正确吗?无论哪种方式,我如何实现这个 IsEmptyOrSpace() 的 Unicode 版本?功能?

编辑: 好的,如果你需要知道为什么 *it >= 0 && *it <= 0x7f测试在那里,我不能告诉你,因为我不知道。我从这个问题的答案中得到了函数的代码:C++ check if string is space or null 所以让我从头开始,一般来说,我如何检查 wstring是 EMPTY 还是空白?

最佳答案

but the two conditions before that will only work with ASCII, right?

没错。他们确保该值符合 isspace 的先决条件:参数“必须具有 unsigned char 或 EOF 的值”。严格来说,你只需要检查*it >= 0,如果char是unsigned,应该优化掉;或者,如评论中所述,您可以将该值转换为 unsigned

iswspace 没有这样的先决条件,所以只需从宽版本中删除这些检查:

bool IsEmptyOrSpaceW(const wstring& str) {
    wstring::const_iterator it = str.begin();

    do {
        if (it == str.end())
            return true;
    } while (iswspace(*(it++)));

    return false;
}

作为样式问题,不需要添加像 W 这样的奇怪的疣来指示参数类型,因为您可以使用不同的参数类型重载 IsEmptyOrSpace

关于C++ 字符串 - 如何为 wstring 实现这个 'IsEmptyOrSpace(string)' 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13378241/

相关文章:

c# - 什么是文本文件中的 ?

c++ - Qt GUI 如何将这些标签放入数组中

C# 从字符串末尾删除子字符串

string - 如何在 Rust 中索引字符串

java、utf8、国际字符和字节解释

python - 使用 python 编码重音字符时出现问题

c++ - 针对 Qt 5.10.1 编译 QtWebKit 5.212 的私有(private) header 问题

c++ - OpenMesh多线程网格导入

C++ 仿函数和零

java - 更新了 util.scanner 重复方法