[英]c++ string iterator “find first of”
字符串迭代器中是否有类似于string上的find_first_of的方法? 就像是:
string::iterator it;
string str(" h asdasf ^& saafa");
it = FIND_FIRST_OF("&az^");
std::cout << *it << std::endl;
结果:
一种
您可以间接做到
auto pos = str.find_first_of("&az^");
然后推进迭代器
if(pos != std::string::npos) // thanks to @Mike Seymour
std::advance(it, pos);
我想您也std::find
使用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_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;
在头文件<algorithm>
中声明了标准算法std::find_first_of
,该<algorithm>
也可以与std :: string类型的对象一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.