string中find函数的使用
9.47 编写程序,首先查找string"ab2c3d7R4E6"中的每个数字字符,然后查找其中每个字母字符。编写两个版本的程序,第一个要使用find_first_of,第二个要使用find_first_not_of。
程序如下:
#include<string>
#include<iostream>
using namespace std;
int main()
{
string::size_type pos=0;
string numbers="0123456789";
string name="ab2c3d7R4E6";
//从pos开始查找name第一次出现在numbers中的字符
while((pos=name.find_first_of(numbers,pos))!=string::npos)
{
cout<<"found number at index: "<<pos<<" element is "<<name[pos]<<endl;
//pos一定要递增,不然就是死循环
pos++;
}
pos=0;
while((pos=name.find_first_not_of(numbers,pos))!=string::npos)
{
cout<<"found char at index: "<<pos<<" element is "<<name[pos]<<endl;
++pos;
}
return 0;
}
运行结果如下: