vivider

string.find()函数用法

1.返回字符串s1在s中的位置,如果没有找到,则返回-1

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
   string s="what are you dong";
   string s1="are";
   int position;
   position=s.find(s1);
   if(position==-1)
    cout<<"not find"<<endl;
   else
    cout<<"position= "<<position<<endl;
   return 0;
}


 

 

2.返回任意字符s1在s中第一次出现的位置,s1为字符,不能为字符串  \'a\'  "a"都可以

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
   string s="hahahaha";
   string s1="a";
   int position;
   position=s.find_first_of(s1);
   cout<<position<<endl;
   return 0;
}

 

3.从字符串s下标为a开始查找字符串s1,返回起始位置  s.find(s1,a); 查找不到返回-1

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
   string s="have a good time";
   string s1="good";
   int position;
   position=s.find(s1,3);
   cout<<position<<endl;
   position=s.find(s1,12);
   cout<<position<<endl;
   return 0;
}

 

4.查找字符s1在s中出现的所有起始位置

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
   string s="abb abb abb";
   string s1="a"; //char s1=\'a\';
   int position=0;
   int i=0;
   while((position=s.find_first_of(s1,position))!=string::npos)
   {
       cout<<position<<endl;
       position++;
       i++;//i为出现的总次数
   }
   cout<<"total="<<i<<endl;
   return 0;
}


 

5.查找字符串s1与s第一个不匹配的位置

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
   string s="aaabcd";
   string s1="aaafcd";
   int position;
   position=s.find_first_not_of(s1);
   cout<<position<<endl;
   return 0;
}


 

6.反向查找,返回s1在s中的位置

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
   string s="aaabcd";
   string s1="abc";
   int position;
   position=s.rfind(s1);
   cout<<position<<endl;
   return 0;
}


 

参考资料:

http://www.jb51.net/article/37560.htm


 

 

 

分类:

技术点:

相关文章:

  • 2021-09-13
  • 2021-07-15
  • 2022-12-23
  • 2021-12-12
  • 2021-07-01
  • 2021-12-12
  • 2021-11-15
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-27
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案