s.find_first_of(args)在s中查找args中的任意字符第一次出现的位置,结果返回string::size_type类型的变量,即查找到位置,下标从0开始
#include <iostream>
#include<string>
using namespace std;
int main() {
string s("ab2c3d7R4E6");
string::size_type pos=0;
string num("0123456789");
cout<<"数字位置:";
string c("qwertyuiopasdfghjklmnbvcxzQWERTYUIOPLKJHGFDSAZXCVBNM");
while((pos=s.find_first_of(num,pos))!=string::npos)
{
cout<<pos<<" ";
++pos;
}
cout<<endl;
pos=0;//注意pos要重新赋值,经过上述循环已达s的末尾,否则将找不到匹配位置
cout<<"字符位置:";
while((pos=s.find_first_of(c,pos))!=string::npos)
{
cout<<pos<<" ";
++pos;
}
cout<<endl;
return 0;
}
结果:
数字位置:2 4 6 8 10
字符位置:0 1 3 5 7 9