字符串迭代器中有一个方法,比如字符串上的find_first_of吗? 类似的东西:
string::iterator it;
string str(" h asdasf ^& saafa");
it = FIND_FIRST_OF("&az^");
std::cout << *it << std::endl;
结果:
一
答案 0 :(得分:6)
你可以间接地做到
auto pos = str.find_first_of("&az^");
然后推进迭代器
if(pos != std::string::npos) // thanks to @Mike Seymour
std::advance(it, pos);
我想你也可以用lambda做某种std::find
,但上面的内容实际上要简单得多。
答案 1 :(得分:4)
我认为std::find_first_of
是您正在寻找的。 p>
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变量所涉及的开销。
答案 2 :(得分:0)
试试这个:
std::string::size_type position = example.find_first_of(".");
if (position != std::string::npos)
{
std::advance(string_iterator, position);
}
else
{
string_iterator = example.end();
}
答案 3 :(得分:0)
除了其他查找方法之外,类std::string
有自己的方法find_first_of
和find_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类型的对象。