关于C++里的find查找函数
本人小白做一下简单的小结。。
先给一下我用的代码这些代码吧:
<span style="color:#ff0000;">#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string s1="love our and you our";
string s2="our";
string s3="myself";
string s4="love";
string s5="or";
string s6="and";
cout<<s1.find(s2)<<endl;;
cout<<s1.find(s3)<<endl;
cout<<s1.find(s4)<<endl<<s1.find(s5)<<endl;
cout<<s1.find_first_of(s6)<<" "<<s1.find_last_of(s6)<<endl;
cout<<s1.find(s2)<<" "<<s1.rfind(s2)<<endl;
int a[6]={1,2,3,4,5,6};
cout<<find(a,a+6,3)<<endl;
cout<<*find(a,a+6,3)<<endl;
char s[12]={"love myself"};
cout<<find(s,s+12,'g')<<endl;
cout<<find(s,s+12,'m')<<endl;
return 0;
}</span><span style="color:#000099;">
</span>
1.首先说一下 在C++中string自带的find函数,其使用规范是 s1.find(s2),意思就是在S1串中寻找是否有S2,如果有则返回串S1中第一次出现串S2的第一个字符,如果没有会返回4294967295这个值,这种查找是一种完全查找,就相当于char类型下的字符串下查找一样
比如说
<span style="color:#ff0000;">cout<<s1.find(s2)<<endl;;
cout<<s1.find(s3)<<endl;</span><span style="color:#ff0000;">cout<<s1.find(s4)<<endl<<s1.find(s5)<<endl;</span>提到过的这些代码输出的便是5
4294967295
0
4294967295
另比较特殊的变形.
s1.find_first_of(s6) s1.find_last_of(s6)
这种的是不完全匹配,及查找到与串S2第一个字符相同时返回他的位置
前者是从前往后查找,后者是从后往前找找到的
这个位置输出的是:
9 11
另外不多见的还有 rfind,他是与find相对应的 从后往前找的
测试实例,提供的代码自行测试.
2.其次是包含在algorithm头文件中的find函数,他的使用方法同sort是相类似的
如所提供代码所示
<span style="color:#ff0000;"> int a[6]={1,2,3,4,5,6};
cout<<find(a,a+6,3)<<endl;
cout<<*find(a,a+6,3)<<endl;
char s[12]={"love myself"};
cout<<find(s,s+12,'g')<<endl;
cout<<find(s,s+12,'m')<<endl;</span>总之就是find(a+begin,a+end)这种格式,他的返回值是指针像第二行代码输出的就是查找到的位置
0x28fec4,第三行代码就是他这个数
没查找到应该就是随机赋值了,具体,自行测试
本文详细介绍了C++中两种查找函数:string类的find方法及其变种,以及<algorithm>库中的find函数。通过实例演示了如何使用这些函数进行字符串和数组元素的查找。
4863

被折叠的 条评论
为什么被折叠?



