I was just talking with a friend about what would be the most efficient way to check if a std::string has only spaces. He needs to do this on an embedded project he is working on and apparently this kind of optimization matters to him.
I've came up with the following code, it uses strtok()
.
bool has_only_spaces(std::string& str) { char* token = strtok(const_cast<char*>(str.c_str()), " "); while (token != NULL) { if (*token != ' ') { return true; } } return false; }
I'm looking for feedback on this code and more efficient ways to perform this task are also welcome.
str. end() ++i) if (! isspace(i)) return false; Pseudo-code, isspace is located in cctype for C++.
Check if a string contains no spaces. The \S character class shortcut will match non-white space characters. To make sure that the entire string contains no spaces, use the caret and the dollar sign: ^\S$.
To check if a string is empty or not, we can use the built-in empty() function in C++. The empty() function returns 1 if string is empty or it returns 0 if string is not empty. Similarly, we can also use the length() function to check if a given string is empty or not. or we can use the size() function.
if(str.find_first_not_of(' ') != std::string::npos) { // There's a non-space. }
In C++11, the all_of
algorithm can be employed:
// Check if s consists only of whitespaces bool whiteSpacesOnly = std::all_of(s.begin(),s.end(),isspace);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With