Find the first character that is not whitespace in a std::string

只愿长相守 提交于 2021-02-19 03:01:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!