Find the first character that is not whitespace in a std::string

c++, stl, string

Solution

This should do it (C++03 compatible, in C++11 you can use a lambda):

#include <cwctype>
#include <functional>

typedef int(*Pred)(std::wint_t);
std::string::iterator it =
    std::find_if( str.begin(), str.end(), std::not1<Pred>(std::iswspace) );

It returns an iterator, subtract `str.begin()` from it if you want an index (or use `std::distance`).

Problem

Lets say I have ``` std::wstring str(L" abc"); ``` The contents of the string could be arbitrary. How can I find the first character that is not whitespace in that string, i.e. in this case the position of the 'a'?

Original source