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

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

    Something like:

    return std::find_if(
                str.begin(), str.end(),
                std::bind2nd( std::not_equal_to(), ' ' ) )
        == str.end();
    

    If you're interested in white space, and not just the space character, then the best thing to do is to define a predicate, and use it:

    struct IsNotSpace
    {
        bool operator()( char ch ) const
        {
            return ! ::is_space( static_cast( ch ) );
        }
    };
    

    If you're doing any text processing at all, a collection of such simple predicates will be invaluable (and they're easy to generate automatically from the list of functions in ).

提交回复
热议问题