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

后端 未结 12 587
别那么骄傲
别那么骄傲 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 05:54

    Hm...I'd do this:

    for (auto i = str.begin(); i != str.end() ++i)
        if (!isspace(i))
           return false;
    

    Pseudo-code, isspace is located in cctype for C++.

    Edit: Thanks to James for pointing out that isspace has undefined behavior on signed chars.

    0 讨论(0)
  • 2020-12-24 05:57

    I do not approve of you const_casting above and using strtok.

    A std::string can contain embedded nulls but let's assume it will be all ASCII 32 characters before you hit the NULL terminator.

    One way you can approach this is with a simple loop, and I will assume const char *.

    bool all_spaces( const char * v )
    {
       for ( ; *v; ++v )
       {
          if( *v != ' ' )
              return false;
       }
       return true;
    }
    

    For larger strings, you can check word-at-a-time until you reach the last word, and then assume the 32-bit word (say) will be 0x20202020 which may be faster.

    0 讨论(0)
  • 2020-12-24 06:02

    Here's one that only uses STL (Requires C++11)

    inline bool isBlank(const std::string& s)
    {
        return std::all_of(s.cbegin(),s.cend(),[](char c) { return std::isspace(c); });
    }
    

    It relies on fact that if string is empty (begin = end) std::all_of also returns true

    Here is a small test program: http://cpp.sh/2tx6

    0 讨论(0)
  • 2020-12-24 06:03

    Why so much work, so much typing?

    bool has_only_spaces(const std::string& str) {
       return str.find_first_not_of (' ') == str.npos;
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 06:05

    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);
    
    0 讨论(0)
提交回复
热议问题