首页 > 编程知识 正文

C++String中的find用法

时间:2023-05-04 20:23:28 阅读:246786 作者:533

#include<string>

string 是c++中一个非常重要函数。

在处理字符串的时候经常用到。

find是string中一个查找函数。

find用法: 1.find()

示例:(上代码)

#include<iostream>#include<string>using namespace std;int main(){string a;string b;getline(cin,a);getline(cin,b);int post=b.find(a);cout<<post<<endl;return 0;}

首先定义两个string类型的变量a和b,getline()是string中的一个方法,从键盘读取一行。

b.find(a);这句代码的意思就是从b字符串中查找a字符串。

公式可以理解为————>母字符串.find(子字符串);

返回值的类型为int类型,返回的是字符串的下标。

#include<iostream>#include<string>using namespace std;int main(){ string st1("babbabab"); cout << st1.find('a') << endl;//1 由原型知,若省略第2个参数,则默认从位置0(即第1个字符)起开始查找 cout << st1.find('a', 0) << endl;//1 cout << st1.find('a', 1) << endl;//1 cout << st1.find('a', 2) << endl;//4 return 0;}

st1.find('a',1);后面的数字代表从什么位置开始查找。如果不加,默认从位置0(即第一个字符)开始查找。

如果你要查找的字符不是单个字母,用法和查找单个字母一样,它会返回第一个字符的位置。

 

2.rfind()

rfind()就是倒着查找。。。。

后面的数字代表着就是从倒数第几个开始查找。

 

 

在这里说一下,如果计算机没有找到,就会返回npos!!

 

if(b.find(a)==string::npos){cout<<"no find"<<endl;}

比如说看这个代码,,如果返回值等于npos,就说明在b字符串里面,没有找到a。

 

3.find_first_of()

        在源串中从位置pos起往后查找,只要在源串中遇到一个字符,该字符与目标串中任意一个字符相同,就停止查找,返回该字符在源串中的位置;若匹配失败,返回npos。

示例

//将字符串中所有的元音字母换成*//代码来自C++ Reference,地址:http://www.cplusplus.com/reference/string/basic_string/find_first_of/#include<iostream>#include<string>using namespace std;int main(){ std::string str("PLease, replace the vowels in this sentence by asterisks."); std::string::size_type found = str.find_first_of("aeiou"); while (found != std::string::npos) { str[found] = '*'; found = str.find_first_of("aeiou", found + 1); } std::cout << str << 'n'; return 0;}//运行结果://PL**s* r*pl*c* th* v*w*ls *n th*s s*nt*nc* by *st*r*sks 4.find_last_of()

 

函数与find_first_of()函数相似,只不过查找顺序是从指定位置向前。

 

5.find_first_not_of()


      在源串中从位置pos开始往后查找,只要在源串遇到一个字符,该字符与目标串中的任意一个字符都不相同,就停止查找,返回该字符在源串中的位置;若遍历完整个源串,都找不到满  足条件的字符,则返回npos。

示例

#include<iostream>#include<string>using namespace std;int main(){ //测试size_type find_first_not_of (const charT* s, size_type pos = 0) const; string str("abcdefg"); cout << str.find_first_not_of("kiajbvehfgmlc", 0) << endl;//3 从源串str的位置0(a)开始查找,目标串中有a(匹配),再找b,b匹配,再找c,c匹配, // 再找d,目标串中没有d(不匹配),停止查找,返回d在str中的位置3 return 0;}

可以复制下来,自己验证一下。

6.find_last_not_of()

find_last_not_of()与find_first_not_of()相似,只不过查找顺序是从指定位置向前。

 

 

                                                                                                               借鉴:https://www.cnblogs.com/zpcdbky/p/4471454.html

 

 

win7电脑文件夹如何加密Struts2的​AJAX标签怎么使用

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