c++find函数用法实验

(1)size_t find (const string& str, size_tpos = 0) const;  //查找对象--string类对象

(2)size_t find (const char* s, size_t pos =0) const; //查找对象--字符串

(3)size_t find (const char* s, size_t pos,size_t n) const;  //查找对象--字符串的前n个字符

(4)size_t find (char c, size_t pos = 0)const;  //查找对象--字符

如果没有找到要查找的对象,find函数会返回string::npos.

可以用if(find(s)== string::npos) break; 结束循环

#include<iostream>

#include<string>

using namespace std;

int main()

{

      string str;

      getline(cin,str);

      intpos[10];

      pos[0]= str.find("abc");//从str中找到abc第一次出现的下标并返回

      pos[1]= str.find("abc",10);//从str第十个元素后开始,找到abc第一次出现的下标

      pos[2]= str.find("abc",10,2);//从str第十个元素后开始,找到ab第一次出现的位置

      pos[3]= str.find_first_of("abc");//从str中找到abc中任意一个字符第一次出现的下标

      pos[4]= str.find_last_of("abc");//从str中找到abc中任意一个最后出现的下标

      pos[5]= str.find_first_not_of("abc");//从str中找到第一个不包含在abc中的元素的下标

      pos[6]= str.find_last_not_of("abc");//从str中找到最后一个不包含在abc中的元素的下标

      pos[7]= str.rfind("abc");//从str从后向前找第一次出现的abc的a的下标

      for(inti = 0;i < 8;i++)

            cout<< pos[i] << " ";

      return0;

}

需要注意的是,npos是string类的静态成员,它的值是string对象能存储的最大字符数,由于索引一般都是从0开始,所以它应该比最大索引大1,因此可以用它来表示没有查找到字符或者字符串。

另外有时会有这种需要:我需要查找一个字符或者字符串第二次、第三次、第n次出现的位置,这时候我们可以用while循环,当所求的下标不满足需要时候,就用find(s,pos+1),其中pos是上一次s出现的位置,s是目标字符。每次循环令pos = str.find(s,pos+1).

代码如下:

#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
getline(cin,str);
int pos = 0;
while(pos != string::npos){
pos = str.find('a',pos+1);//输出a在str中的下标,直到结束。
cout << pos << " ";

return 0;

}

最后要提到的是,find()函数返回的值并不是严格的int型,有些时候上述写法会出错,保险的用法是把上述while内条件改为(str.find('a',pos+1) != string::npos).

原文地址:https://www.cnblogs.com/long98/p/10352271.html