Pattern Matching Program in C++

We can perform pattern matching method in C++ Language. Pattern matching is nothing but a searching algorithm which is used to find a sequence from a long string. A long string may contains many founded sequence.

When you found a sequence then it finds the location of the sequence and prints it. This searching algorithm used to find the coding in computer programs.

You don’t want to take risks to find a single small sequence. You can search it by pattern matching. The below program runs on Linux system. This algorithm is also called as Naïve String algorithm.

pattern-matching-program-in-cpp

Pattern Matching Program in C++

#include<stdio.h>
#include<string.h>
void search(char *pat, char *txt)
{
    int M = strlen(pat);
    int N = strlen(txt);
 
    /* A loop to slide pat[] one by one */
    for (int i = 0; i <= N - M; i++)
    {
        int j;
 
        /* For current index i, check for pattern match */
        for (j = 0; j < M; j++)
        {
            if (txt[i + j] != pat[j])
                break;
        }
        if (j == M) // if pat[0...M-1] = txt[i, i+1, ...i+M-1]
        {
            printf("Pattern found at index %d \n", i);
        }
    }
}
 
/* Driver program to test above function */
int main()
{
    char *txt = "AABAACAADAABAAABAA";
    char *pat = "AABA";
    search(pat, txt);
    return 0;
}

You can also perform pattern matching in C language. I just gave an another article to perform pattern matching in C language. Check my other articles to know more about coding’s.

Read Also : Find Transpose of a Matrix in C++

Output

$ g++ StringMatchingNaive.cpp
$ a.out
 
Pattern found at index 0 
Pattern found at index 9 
Pattern found at index 13 
------------------
(program exited with code: 0)
Press return to continue

Final Words

I hope this article helps you to Pattern Matching Program in C++ Program. If you face any issues please let me know via the comment section. Share this article with other C++ program developers via social networks.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment