c++ string类字符串查找

c++ string类字符串查找1 find 函数 find 函数用于在 string 字符串中查找子字符串出现的位置 它其中的两种原型为 size tfind conststring amp str size tpos 0 const size tfind constchar s size tpos 0 const 第一个参数为待查找的子字符串 它可以是 string 字符串 也可以是 C 风格的字符串 第二个参数为开始查找的位置 下标 如果不指明 则从第 0 个字符开始查找 请看下面的

1) find() 函数

find() 函数用于在 string 字符串中查找子字符串出现的位置,它其中的两种原型为:

size_t find (const string& str, size_t pos = 0) const; size_t find (const char* s, size_t pos = 0) const; 

第一个参数为待查找的子字符串,它可以是 string 字符串,也可以是C风格的字符串。第二个参数为开始查找的位置(下标);如果不指明,则从第0个字符开始查找。

请看下面的代码:

#include  
     #include  
     using namespace std; int main(){ 
    string s1 = "first second third"; string s2 = "second"; int index = s1.find(s2,5); if(index < s1.length()) cout<<"Found at index : "<< index <<endl; else cout<<"Not found"<<endl; return 0; } 

运行结果:

Found at index : 6

find() 函数最终返回的是子字符串第一次出现在字符串中的起始下标。本例最终是在下标6处找到了 s2 字符串。如果没有查找到子字符串,那么会返回一个无穷大值 。

2) rfind() 函数

rfind() 和 find() 很类似,同样是在字符串中查找子字符串,不同的是 find() 函数从第二个参数开始往后查找,而 rfind() 函数则最多查找到第二个参数处,如果到了第二个参数所指定的下标还没有找到子字符串,则返回一个无穷大值。

请看下面的例子:

#include  
     #include  
     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; } 

3) find_first_of() 函数

find_first_of() 函数用于查找子字符串和字符串共同具有的字符在字符串中首次出现的位置。请看下面的代码:

#include  
     #include  
     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; } 

本例中 s1 和 s2 共同具有的字符是 ’s’,该字符在 s1 中首次出现的下标是3,故查找结果返回3。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/229400.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月16日 下午4:48
下一篇 2026年3月16日 下午4:48


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号