Skip to content
Related Articles

Related Articles

Pattern Searching using C++ library
  • Difficulty Level : Easy
  • Last Updated : 26 Mar, 2018

Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function that prints all occurrences of pat[] in txt[]. You may assume that n > m.

Examples:

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

The idea is to use find() in C++ string class.




// CPP program to print all occurrences of a pattern
// in a text
#include <bits/stdc++.h>
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;
}
Output:
Pattern found at index 0
Pattern found at index 1
Pattern found at index 2
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :