在std::string中找到第一个非空格字符

4
假设我有:
std::wstring str(L"   abc");

字符串的内容可以是任意的。

如何找到该字符串中第一个非空格字符的位置,即在此例中为 'a' 的位置?

2个回答

5

使用 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);

这是否适用于所有空白字符,如 '\n'? - Christian
@Christian 是的,find_first_not_of有几个重载。请看我的更新,希望能有所帮助。 - billz

4
这应该可以做到(兼容C++03,在C++11中可以使用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) );

该函数返回一个迭代器,如果您需要索引,请从中减去 str.begin()(或使用std::distance)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接