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

后端 未结 12 652
别那么骄傲
别那么骄傲 2020-12-24 05:20

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 worki

12条回答
  •  失恋的感觉
    2020-12-24 06:11

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

提交回复
热议问题