Norway


Given a text txt[0..n-1] and a 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 

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++.

// 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


- avatar - Pattern Searching using C++ library

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.







Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here