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

后端 未结 12 705
别那么骄傲
别那么骄傲 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:03

    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.

提交回复
热议问题