string类成员函数find/find_first_of用法详解

本文详细解析了C++中字符串方法find与find_first_of的功能与用法,通过示例展示了如何定位子字符串及特定字符的位置,并强调了两者之间的主要区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


一:find

函数原型:

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

参数说明:pos查找起始位置    n待查找字符串的前n个字符

使用样例:

string  str1(“the usage of find can you use it”);

string  str2(“the”);

上面定义出了两个字符串;

str1.find(str2);                    //  从串str1中查找时str2,返回str2中首个字符在str1中的地址

str1.find(str2,5);                //   从str1的第5个字符开始查找str2

str1.find(“usage”);            //   如果usage在str1中查找到,返回u在str1中的位置

str1.find(“o”);                     //   查找字符o并返回地址

str1.find(“of big”,2,2);      //   从str1中的第二个字符开始查找of big的前两个字符

 

二:find_first_of

函数原型:

size_t find_first_of ( const string& str, size_t pos = 0 ) const;
size_t find_first_of ( const char* s, size_t pos, size_t n ) const;
size_t find_first_of ( const char* s, size_t pos = 0 ) const;
size_t find_first_of ( char c, size_t pos = 0 ) const;

参数和find基本相同,不在赘述!

特别注意:

find_first_of 函数最容易出错的地方是和find函数搞混。它最大的区别就是如果在一个字符串str1中查找另一个字符串str2,如果str1中含有str2中的任何字符,则就会查找成功,而find则不同;

比如:

string str1(“I am change”);

string  str2(“about”);

int k=str1.find_first_of(str2);    //k返回的值是about这5个字符中任何一个首次在str1中出现的位置;

 

 

  1. //the usage of find /find_first_of by heat_nan from ZZULI
  2. #include<iostream>
  3. #include<string>
  4. using namespace std;
  5. int main()
  6. {
  7. string str1(”Hi,every one! I am heat_nan from ZZULI. one”);
  8. string str2(”heat_nan”);
  9. int k=str1.find(str2);
  10. cout<<“The position of ‘heat_nan’ is “<<k<<endl;
  11. int k1=str1.find(“one”);
  12. cout<<“The postion of the first ‘one’ is “<<k1<<endl;
  13. int k2=str1.find(“one of”,k1+1,3);
  14. cout<<“The postion of the second ‘one’ is “<<k2<<endl;
  15. int k3=str1.find_first_of(“aeiou”);//here k3=1
  16. while(k3!=string::npos) //hint: here “string::npos”means find failed
  17. {
  18. str1[k3]=‘*’;
  19. k3=str1.find_first_of(“aeiou”,k3+1);
  20. }
  21. cout<<str1<<endl;
  22. return 0;
  23. }


 

            </div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值