假设我有:
std::wstring str(L" abc");
字符串的内容可以是任意的。
如何找到该字符串中第一个非空格字符的位置,即在此例中为 'a' 的位置?
使用 std::basic_string::find_first_not_of
函数。
std::wstring::size_type pos = str.find_first_not_of(' ');
pos是3
更新:要查找其他任何字符
const wstring delims(L" \t,.;");
std::wstring::size_type pos = str.find_first_not_of(delims);
#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) );
该函数返回一个迭代器,如果您需要索引,请从中减去 str.begin()
(或使用std::distance
)。