C++中的string find函数用法示例

2021年3月17日18:15:43 发表评论 832 次浏览

String find用于查找被调用的指定字符串中子字符串的首次出现。它从给定的起始位置返回字符串中子字符串首次出现的索引。起始位置的默认值为0。

功能模板:

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

功能参数:

  • str:要搜索的子字符串。
  • s:要搜索的子字符串, 以C样式字符串形式给出。
  • pos:字符串搜索开始的初始位置。

函数返回:

  • 函数返回第一次出现的子字符串的索引, 如果未找到子字符串, 则返回string :: npos(string :: pos是静态成员, 其值对于size_t数据结构而言为最大)。
// CPP program to demonstrate working of string
// find to search a string
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
     string str = "lsbin a computer science" ;
     string str1 = "geeks" ;
  
     // Find first occurrence of "geeks"
     size_t found = str.find(str1);
     if (found != string::npos)
         cout << "First occurrence is " << found << endl;
  
     // Find next occurrence of "geeks". Note here we pass
     // "geeks" as C style string.
     char arr[] = "geeks" ;
     found = str.find(arr, found+1);
     if (found != string::npos)
         cout << "Next occurrence is " << found << endl;
  
     return 0;
}

输出如下:

First occurrence is 0
Next occurrence is 8

我们还可以使用它来查找字符的出现:

在下面的语法中, 请注意c是一个字符。

  • size_t find(const char c, size_t pos = 0);
// CPP program to demonstrate working of string
// find to search a string
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
     string str = "lsbin a computer science" ;
     char c = 'g' ;
  
     // Find first occurrence of 'g'
     size_t found = str.find(c);
     if (found != string::npos)
         cout << "First occurrence is " << found << endl;
  
     // Find next occurrence of 'g'
     found = str.find(c, found+1);
     if (found != string::npos)
         cout << "Next occurrence is " << found << endl;
  
     return 0;
}

输出如下:

First occurrence is 0
Next occurrence is 8

我们还可以搜索部分字符串

在以下语法中, 请注意n是要匹配的字符数。

  • size_t find(const char * str, size_t pos, size_t n);
// CPP program to demonstrate working of string
// find to search a string
#include <iostream>
#include <string>
  
using namespace std;
  
int main()
{
     string str = "lsbin a computer science" ;
  
     // Only search first 5 characters of "geeks.practice"
     size_t found = str.find( "geeks.practice" , 0, 5);
     if (found != string::npos)
         cout << found << endl;
  
     return 0;
}

输出如下:

0

被认为是行业中最受欢迎的技能之一, 我们拥有自己的编码基础C ++ STL通过激烈的问题解决过程来训练和掌握这些概念。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: