Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to check if std::string has only spaces

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.

like image 695
karlphillip Avatar asked Jun 22 '11 18:06

karlphillip


People also ask

How do you check if a string only contains spaces C++?

str. end() ++i) if (! isspace(i)) return false; Pseudo-code, isspace is located in cctype for C++.

How do you make sure a string has no spaces?

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$.

How check string is empty or not in C++?

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.


2 Answers

if(str.find_first_not_of(' ') != std::string::npos) {     // There's a non-space. } 
like image 163
Mark B Avatar answered Oct 11 '22 14:10

Mark B


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); 
like image 22
Michael Goldshteyn Avatar answered Oct 11 '22 14:10

Michael Goldshteyn