关于字符串的各种查找
原文出处:https://www.cnblogs.com/yongpan/p/7920165.html
1 find函数:在字符串中查找子字符串中出现的位置
- 函数最终返回的是子字符串出现在字符串中的起始下标
- 该函数有两个参数,第一个参数是待查找的子字符串
- 第二个参数是表示开始查找的位置(默认从0开始查找)
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1 = "first second third";
string s2 = "second";
int index = s1.find(s2,0);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}
输出结果为:Found at index : 6
2 rfind函数:在字符串中查找子字符串
- 与find函数不同的是最多查找到第二个参数处
- 如果到了第二个参数所指定的下标还没有找到子字符串,则返回一个无穷大值
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "first second third";
string s2 = "second";
int index = s1.rfind(s2,6);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}
输出结果为:Found at index : 6
3 find_first_of函数:查找子字符串和字符串共同具有的字符在字符串中出现的位置
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "first second second third";
string s2 = "asecond";
int index = s1.find_first_of(s2);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}
4 find_first_not_of函数:查找在s1字符串但不在s2字符串中的首位字符的下标
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "secondasecondthird";
string s2 = "asecond";
int index = s1.find_first_not_of(s2);
if(index < s1.length())
cout<<"Found at index : "<< index <<endl;
else
cout<<"Not found"<<endl;
return 0;
}