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

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

    it's highly unlikely you'll beat a compiler optimized naive algorithm for this, e.g.

    string::iterator it(str.begin()), end(str.end())    
    for(; it != end && *it == ' '; ++it);
    return it == end;
    

    EDIT: Actually - there is a quicker way (depending on size of string and memory available)..

    std::string ns(str.size(), ' '); 
    return ns == str;
    

    EDIT: actually above is not quick.. it's daft... stick with the naive implementation, the optimizer will be all over that...

    EDIT AGAIN: dammit, I guess it's better to look at the functions in std::string

    return str.find_first_not_of(' ') == string::npos;
    

提交回复
热议问题