c++之string.find(string)

先来看一个例子吧:

#include "iostream"

#include "string"

using namespace std;

// 定义函数求str2在是str1中出现的次数

int occurrer_number(string str1,string str2)

{

        int pos;                 // 记下要查找的字符(串)在字符串中的位置

      int k=0;                 // 该字符(串)出现的次数

     int pos1=-1;

     // 输入字符串

     cout<<"请输入一串字符:"<<endl;

     cin>>str1;      // 输入要查找的字符串

     cout<<"请输入要查找的字符(串):"<<endl;

     cin>>str2;

        // 先找到第一个位置

     pos=str1.find(str2);

     if(pos!=-1)

  {

         k++;   

  }

     // 开始数,str1在str中出现的次数;

    for(;;)    

    {         

    pos=str1.find(str2,pos+str2.length());      // 查找之后还有没有str1,如果没有会将-1赋给pos

      if(pos==pos1)

         {                 break;       // 直到pos变成-1时跳出          }

         else         {                 k++;         // 若不是-1,则出现的次数+1         }

       }

    return k;    // 返回次数

}

void main()

{  

string str1,str2;       // 定义两个字符串变量  int show_num;           // 出现的次数

 // 调用求解次数的函数int occurrer_number(string str1,string str2)  show_num=occurrer_number(str1,str2);

 cout<<"共出现"<<show_num<<"次该字符(串)"<<endl;

}


find函数的运用时,如果找到就返回位置,找不到返回的是-1

 

posted @ 2015-12-03 18:04  cxccc  阅读(802)  评论(0编辑  收藏  举报