类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 也可以用于std::string 类型的对象。