【问题标题】:Find the first character that is not whitespace in a std::string在 std::string 中查找不是空格的第一个字符
【发布时间】:2014-03-26 10:47:33
【问题描述】:

假设我有

std::wstring str(L"   abc");

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

如何找到该字符串中第一个不是空格的字符,即在本例中是“a”的位置?

【问题讨论】:

    标签: c++ string stl


    【解决方案1】:

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

    【讨论】:

    • 这是否适用于所有空白字符,如 '\n'?
    • @Christian 是的,find_first_not_of 有一些重载。查看我的更新,希望对您有所帮助
    【解决方案2】:

    应该这样做(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)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-24
      • 2017-01-26
      • 2012-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 2017-09-22
      相关资源
      最近更新 更多