首页 > 编程知识 正文

String find函数(详解,很容易懂)

时间:2023-05-04 09:48:48 阅读:214734 作者:1881

#include<cstring>#include<cstdio>#include<iostream>using namespace std;int main(){//find函数返回类型 size_typestring s("1a2b3c4d5e6f7jkg8h9i1a2b3c4d5e6f7g8ha9i");string flag;string::size_type position;//写成int也行//find 函数 返回 "3c4" 在s 中的首次下标位置,也就是第一个字符的首次位置,这里是4position = s.find("3c4");if (position != s.npos) //如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295,写成-1也行,计算机中和npos相等//即if (position != -1){printf("position is : %dn" ,position);}else{printf("Not found the flagn");}}

查找某一给定位置后的子串的位置
1 //从字符串s 下标5开始,(包括5!!)查找字符串b ,返回b 在s 中的下标
2 position=s.find(“b”,5);

下面举例

#include<cstring>#include<cstdio>#include<iostream>using namespace std;int main(){//find函数返回类型 size_typestring s("1a2b3c43d5e6f7jkg8h9i1a2b3c4d5e6f7g8ha9i");string flag;string::size_type position;//find 函数 返回3 在s 中的下标位置 position=4; int i=1; while((position=s.find('3',position))!=string::npos) { cout<<"position "<<i<<" : "<<position<<endl; position++; i++; } return 0;}//输出position 1 : 4position 2 : 7position 3 : 25 #include<cstring>#include<cstdio>#include<iostream>using namespace std;int main(){//find函数返回类型 size_typestring s("1a2b3c43d5e6f7jkg8h9i1a2b3c4d5e6f7g8ha9i");string flag;string::size_type position;//find 函数 返回3 在s 中的下标位置 position=5; int i=1; while((position=s.find("3",position))!=-1) { cout<<"position "<<i<<" : "<<position<<endl; position++; i++; } return 0;}//输出position 1 : 7position 2 : 25

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。