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

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

提交回复
热议问题