📜  使用C ++库进行模式搜索

📅  最后修改于: 2021-05-31 19:22:08             🧑  作者: Mango

给定文本txt [0..n-1]和模式pat [0..m-1],编写一个函数来打印txt []中所有出现的pat []。您可以假设n> m。

例子:

Input : txt[] = "geeks for geeks"
        pat[] = "geeks"
Output : Pattern found at index 0
         Pattern found at index 10

Input : txt[] = "aaaa"
        pat[] = "aa"
Output : Pattern found at index 0
         Pattern found at index 1
         attern found at index 2

这个想法是在C++字符串类中使用find()。

// CPP program to print all occurrences of a pattern
// in a text
#include 
using namespace std;
  
void printOccurrences(string txt, string pat)
{
    int found = txt.find(pat);
    while (found != string::npos) {
        cout << "Pattern found at index " << found << endl;
        found = txt.find(pat, found + 1);
    }
}
  
int main()
{
    string txt = "aaaa", pat = "aa";
    printOccurrences(txt, pat);
    return 0;
}
输出:
Pattern found at index 0
Pattern found at index 1
Pattern found at index 2
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”