问题
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'?
回答1:
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
).
回答2:
use [std::basic_string::find_first_not_of][1]
function
std::wstring::size_type pos = str.find_first_not_of(' ');
pos is 3
Update: to find any other chars
const wstring delims(L" \t,.;");
std::wstring::size_type pos = str.find_first_not_of(delims);
来源:https://stackoverflow.com/questions/22658597/find-the-first-character-that-is-not-whitespace-in-a-stdstring