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

C++ Strings - How can I implement this 'IsEmptyOrSpace(string)' method for wstring's?

本文关键字:IsEmptyOrSpace string 方法 字符串 实现 wstring C++      更新时间:2023-10-16

好的,我在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++检查字符串是空格还是空因此,让我从头开始,一般来说,我如何检查wstring是空的还是只是空格?

但在此之前的两个条件仅适用于 ASCII,对吧?

没错。他们确保值符合isspace的前提条件:参数"必须具有unsigned char或EOF的值"。严格来说,您只需要*it >= 0检查,如果char未签名,则应对其进行优化;或者,如注释中所述,您可以将值转换为 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

bool IsEmptyOrSpaceW(const wstring& str) {
  return str.length() == (size_t)std::count(str.begin(), str.end(), L' ');
}

// this code works for string and wstring
    template <typename CharType>
    bool IsEmptyOrSpace(const std::basic_string<CharType>& str)  {
      return str.length() == (size_t)std::count(str.begin(), str.end(), CharType(32));
    }

实际上,还有其他类型的空格,例如制表符, 我对这段代码是否处理这些并不肯定 空格字符。

如果我们想处理所有这些空格字符,我们可以找到 isspace 函数返回 false 的第一个符号

template <typename CharType>
bool IsEmptyOrSpace(const std::basic_string<CharType>& str)  {
  return str.end() == std::find_if(str.begin(), str.end(), 
          std::not1(std::ptr_fun((int(*)(int))isspace)));
}