C++中如何使用string.find()函数

发布时间:2021-07-28 14:28:58 作者:Leah
来源:亿速云 阅读:161

这篇文章将为大家详细讲解有关C++中如何使用string.find()函数,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

#include <string>#include <iostream>using namespace std; void main(){复制代码 代码如下: ////find函数返回类型 size_typestring s("1a2b3c4d5e6f7g8h9i1a2b3c4d5e6f7g8ha9i");string flag;string::size_type position;//find 函数 返回jk 在s 中的下标位置 position = s.find("jk");if (position != s.npos) //如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295,{cout << "position is : " << position << endl;}else{cout << "Not found the flag" + flag;}复制代码 代码如下: //find 函数 返回flag 中任意字符 在s 中第一次出现的下标位置flag = "c";position = s.find_first_of(flag);cout << "s.find_first_of(flag) is : " << position << endl;复制代码 代码如下: //从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标position=s.find("b",5);cout<<"s.find(b,5) is : "<<position<<endl;复制代码 代码如下: //查找s 中flag 出现的所有位置。flag="a";position=0;int i=1;while((position=s.find_first_of(flag,position))!=string::npos){ //position=s.find_first_of(flag,position); cout<<"position "<<i<<" : "<<position<<endl; position++; i++;}复制代码 代码如下: //查找flag 中与s 第一个不匹配的位置flag="acb12389efgxyz789";position=flag.find_first_not_of (s);cout<<"flag.find_first_not_of (s) :"<<position<<endl;复制代码 代码如下: //反向查找,flag 在s 中最后出现的位置flag="3";position=s.rfind (flag);cout<<"s.rfind (flag) :"<<position<<endl;}

说明:1.如果string sub = ”abc“;string s = ”cdeabcigld“;s.find(sub) , s.rfind(sub) 这两个函数,如果完全匹配,才返回匹配的索引,即:当s中含有abc三个连续的字母时,才返回当前索引。s.find_first_of(sub), s.find_first_not_of(sub), s.find_last_of(sub), s.find_last_not_of(sub) 这四个函数,查找s中含有sub中任意字母的索引。

2.如果没有查询到,则返回string::npos,这是一个很大的数,其值不需要知道。

关于C++中如何使用string.find()函数就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

推荐阅读:
  1. php连接mysql数据库的方法有哪些
  2. go语言相对于c/c++的优势有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++ string.find()

上一篇:如何使用Xcode7的Instruments检测解决iOS内存泄露问题

下一篇:IOS中多手势之间冲突怎么办

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》