Okay, I searched StackOverflow on how to check if a string is empty or just whitespace. But, it only works with ANSI strings. How can I get it to work with a wstring?
Here is the code:
#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;
}
My first thought was to change isspace(*(it++)) to iswspace(*(it++)), but the two conditions before that will only work with ASCII, right? Here is what I have so far on attempting to adapt the function to wstring‘s:
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;
}
Is my approach close to being correct? Either way, how can I implement a Unicode version of this IsEmptyOrSpace() function?
EDIT:
Okay, if you need to know why the *it >= 0 && *it <= 0x7f test is there, I cannot tell you, because I do not know. I got the code for the function from the answer to this question: C++ check if string is space or null
So let me start from scratch, how, in general, may I check if a wstring is EMPTY or just whitespace?
That’s right. They make sure the value conforms to the precondition of
isspace: the argument “must have the value of anunsigned charor EOF”. Strictly speaking, you only need the*it >= 0check, which should be optimised out ifcharis unsigned; alternatively, as mentioned in the comments, you could convert the value tounsigned.iswspacehas no such precondition, so just remove those checks from the wide version:As a matter of style, there’s no need to add a strange wart like
Wto indicate the parameter type, since you can just overloadIsEmptyOrSpacewith different parameter types.