好的,我在 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/