形式

  1. size_t find ( const string& str, size_t pos = 0 ) const;
  2. size_t find ( const char* s, size_t pos = 0 ) const;
  3. size_t find ( char c, size_t pos = 0 ) const;
  4. size_t find ( const **char s , size_t pos, size_t n** ) const;*

**

参数说明

  1. pos 查找的起始位置
  2. n 待查找字符串的前n个字符

**

使用样例

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

注意

  1. size_t std::size_t 长度类型
  2. string 中 find() 返回值是字母在串中的位置(下标而不是迭代器)
  3. 若没找到,那么会返回一个特别的标记npos(可以看成是一个int型的数)**

    例子演示

👀1.size_t find ( const **string& str, size_t pos = 0 ) const; 形参是字符串**

作用:在串str1中查找串str2,并返回str1中的str2的首个字符地址下标

  1. string str1( "the usage of find can you use it");
  2. string str2( "find");
  3. std::size_t pos;
  4. pos=str1.find(str2); //str2是字符串


作用:在串str1的第5个字符开始**查找str2,并返回str1中的str2的首个字符地址下标

  1. string str1( "the usage of find can you use it");
  2. string str2( "find");
  3. std::size_t pos;
  4. pos=str1.find(str2,5); //str2是字符串

👀2.size_t find ( const char* s, size_t pos = 0 ) const; 形参是字符数组

作用:在串str1中查找字符数组”usage”,并返回返回”usage”在str1中的下标位置

  1. string str1( "the usage of find can you use it");
  2. string str2( "find");
  3. std::size_t pos;
  4. pos=str1.find("usage"); //"usage"是字符数组

👀3.size_t find ( char c, size_t pos = 0 ) const; 形参是字符

作用:在串str1中查找字符 o,并返回 o 的地址下标位置

注意
字符或者字符串都可以正常使用

  1. string str1( "the usage of find can you use it");
  2. string str2( "find");
  3. std::size_t pos;
  4. pos=str1.find("o"); //"o"是字符串
  5. pos=str1.find("o"); //'o'是字符

**

👀4.size_t find ( const **char s , size_t pos, size_t n ) const; 形参是字符数组*

作用:从str1中的第二个字符开始查找of big的前两个字符

解释:

  • string str1( “the usage of find can you use it”);
  • string str2( “the”);
    1. 第一句:str1的第二个字符开始,指的是 th**e usage of find can you use it 从e开始 **
    2. 第二句:str2的前两个字符,指的是 of** big 中的 **of

**

  1. string str1( "the usage of find can you use it");
  2. string str2( "the");
  3. std::size_t pos;
  4. pos=str1.find("of big",2,2);

结果演示

  1. # include<iostream>
  2. # include<algorithm>
  3. using namespace std;
  4. int main(void)
  5. {
  6. string str1("the usage of find can you use it");
  7. string str2("the");
  8. std::size_t pos;
  9. pos = str1.find(str2); //从串str1中查找时str2,返回str2中首个字符在str1中的地址
  10. pos = str1.find(str2, 5); //从str1的第5个字符开始查找str2
  11. pos = str1.find("usage"); //如果"usage"在str1中查找到,返回u在str1中的位置
  12. pos = str1.find('o'); //查找字符o并返回地址
  13. pos = str1.find("e big", 2, 2); //从str1中的第二个字符开始查找of big的前两个字符
  14. }
  15. /*
  16. str1="the usage of find can you use it"
  17. str2="the"
  18. 0
  19. 4294967295
  20. 4
  21. 10
  22. 2
  23. */