C++ 字符串迭代器"find first of"
c++ string iterator "find first of"
字符串迭代器中的方法是否有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_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的对象一起使用。
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- C++算法标头中,为什么要使用 "!(val < *first)" ?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- C++ 字符串迭代器"find first of"
- "Multiple definition of.." "First defined here"数据结构中的同一行中