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

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

    Using strtok like that is bad style! strtok modifies the buffer it tokenizes (it replaces the delimiter chars with \0).

    Here's a non modifying version.

    const char* p = str.c_str();
    while(*p == ' ') ++p;
    return *p != 0;
    

    It can be optimized even further, if you iterate through it in machine word chunks. To be portable, you would also have to take alignment into consideration.

提交回复
热议问题