【发布时间】:2014-03-26 10:47:33
【问题描述】:
假设我有
std::wstring str(L" abc");
字符串的内容可以是任意的。
如何找到该字符串中第一个不是空格的字符,即在本例中是“a”的位置?
【问题讨论】:
假设我有
std::wstring str(L" abc");
字符串的内容可以是任意的。
如何找到该字符串中第一个不是空格的字符,即在本例中是“a”的位置?
【问题讨论】:
使用[std::basic_string::find_first_not_of][1]函数
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);
【讨论】:
应该这样做(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)。
【讨论】: