This is a C++ Program to perform Naive String matching algorithm. In computer science, string searching algorithms, sometimes called string matching algorithms, are an important class of string algorithms that try to find a place where one or several strings (also called patterns) are found within a larger string or text.
Here is source code of the C++ Program to Perform Naive String Matching. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
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++)
/* For current index i, check for pattern match */
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
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 */
char *txt = "AABAACAADAABAAABAA";
char *pat = "AABA";
$ g++ StringMatchingNaive.cpp
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13
(program exited with code: 0)
Press return to continue
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Here’s the list of Best Books in C++ Programming, Data Structures and Algorithms.
- Get Free Certificate of Merit in C++ Programming
- Participate in C++ Programming Certification Contest
- Become a Top Ranker in C++ Programming
- Take C++ Programming Tests
- Chapterwise Practice Tests: Chapter 1,
- Chapterwise Mock Tests: Chapter 1,
, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry
. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms.
Stay connected with him at LinkedIn
Subscribe to his free Masterclasses at Youtube
& technical discussions at Telegram SanfoundryClasses