📜  在C++中找到字符串

📅  最后修改于: 2021-05-30 04:16:31             🧑  作者: Mango

字符串查找用于查找被调用的指定字符串中子字符串的首次出现。它返回从给定的起始位置的字符串中的字符串的第一个出现的索引。起始位置的默认值为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:字符串搜索开始的初始位置。

函数返回:

  • 该函数返回第一次出现的子字符串的索引,如果未找到该子字符串,则返回字符串:: npos(字符串:: pos是静态成员,其值对于size_t数据结构为最大值)。
// CPP program to demonstrate working of string
// find to search a string
#include 
#include 
  
using namespace std;
  
int main()
{
    string str = "geeksforgeeks 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 
#include 
  
using namespace std;
  
int main()
{
    string str = "geeksforgeeks 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 
#include 
  
using namespace std;
  
int main()
{
    string str = "geeksforgeeks 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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”