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

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);

Why so much work, so much typing?

bool has_only_spaces(const std::string& str) {
   return str.find_first_not_of (' ') == str.npos;
}

Wouldn't it be easier to do:

bool has_only_spaces(const std::string &str)
{
    for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)
    {
        if (*it != ' ') return false;
    }
    return true;
}

This has the advantage of returning early as soon as a non-space character is found, so it will be marginally more efficient than solutions that examine the whole string.


To check if string has only whitespace in c++11:

bool is_whitespace(const std::string& s) {
  return std::all_of(s.begin(), s.end(), isspace);
}

in pre-c++11:

bool is_whitespace(const std::string& s) {
  for (std::string::const_iterator it = s.begin(); it != s.end(); ++it) {
    if (!isspace(*it)) {
      return false;
    }
  }
  return true;
}