C++ 字符串迭代器"find first of"

c++ string iterator "find first of"

本文关键字:first of find C++ 迭代器 字符串      更新时间:2023-10-16

字符串迭代器中的方法是否有find_first_of在字符串上?类似:

string::iterator it;
string str("  h asdasf ^& saafa");
it = FIND_FIRST_OF("&az^");
std::cout << *it << std::endl;

和结果:

a

您可以间接地做

auto pos = str.find_first_of("&az^");

然后推进迭代器

if(pos != std::string::npos) // thanks to @Mike Seymour
    std::advance(it, pos);

我想您也可以使用lambda进行某种std::find,但是上面的实际上更简单和简洁。

我认为std::find_first_of是您要寻找的。

string::iterator it;
string str("  h asdasf ^& saafa");
string find_me ("&az^");
it = std::find_first_of (str.begin(), str.end(), find_me.begin(), find_me.end());
std::cout << *it << std::endl;

我会编写一个函数,以清理构造/使用中介find_me变量的台式,如果使用此方法以任何频率使用。

尝试以下:

std::string::size_type position = example.find_first_of(".");
if (position != std::string::npos)
{
  std::advance(string_iterator, position);
}
else
{
  string_iterator = example.end();
}

std::string具有其自己的方法find_first_offind_last_of,除其他查找方法。

这是一个指示的程序

#include <iostream>
#include <string>
int main() 
{
    std::string s( "  h asdasf ^& saafa" );
    auto pos = s.find_first_of( "&az^" );
    if ( pos != std::string::npos ) std::cout << s[pos] << std::endl;
    pos = s.find_last_of( "&az^" );
    if ( pos != std::string::npos ) std::cout << s[pos] << std::endl;
    return 0;
}

程序输出是

a
a

这是另一个示范程序,该程序在字符文字

中指定的字符串中的所有字符
#include <iostream>
#include <string>
int main() 
{
    std::string s( "  h asdasf ^& saafa" );
    for ( std::string::size_type pos = 0; 
          ( pos = s.find_first_of( "&az^", pos ) ) != std::string::npos;
          ++pos )
    {
        std::cout << pos << ": " << s[pos] << std::endl;
    }        
    return 0;
}

程序输出是

4: a
7: a
11: ^
12: &
15: a
16: a
18: a

知道您始终可以在对象中获取相应的迭代器的位置:

std::string::iterator it = std::next( s.begin(), pos );

auto it = std::next( s.begin(), pos );

或简单

std::string::iterator it = s.begin() + pos;

另外,标准算法std::find_first_of在标题<algorithm>中声明,也可以与类型std :: string的对象一起使用。