Recursive function to do substring search

Given a text txt[] and a pattern pat[], write a recursive function “contains(char pat[], char txt[])” that returns true if pat[] is present in txt[], otherwise false.

Examples:

1) Input:   txt[] =  "THIS IS A TEST TEXT"
            pat[] = "TEST"
  Output:  true


2) Input:  txt[] =  "geeksforgeeks"
           pat[] = "quiz"
  Output:  false;

We strongly recommend to minimize the browser and try this yourself first.

Below is recursive algorithm.

contains(tex[], pat[])
    1) If current character is last character of text, but pat
       has more characters, return false.

    2) Else If current character is last character of pattern,
       then return true

    3) Else If current characters of pat and text match, then
        return contains(text + 1, pat + 1);

    4) Else If current characters of pat and text don't match
        return contains(text + 1, pat);

Below is C++ implementation of above algorithm.

// Recursive C++ program to find if a given pattern is 
// present in a text
#include<iostream>
using namespace std;

bool exactMatch(char *text, char *pat)
{
    if (*text == '\0' && *pat != '\0')
        return false;

    // Else If last character of pattern reaches
    if (*pat == '\0')
        return true;

    if (*text == *pat)
        return exactMatch(text + 1, pat + 1);

    return false;
}

// This function returns true if 'text' contain 'pat'
bool contains(char *text, char *pat)
{
    // If last character of text reaches
    if (*text == '\0')
        return false;

    // If current characts of pat and text match
    if (*text == *pat)
        return exactMatch(text, pat);

    // If current characts of pat and tex don't match
    return contains(text + 1, pat);
}

// Driver program to test above function
int main()
{
    cout << contains("geeksforgeeks", "geeks") << endl;
    cout << contains("geeksforgeeks", "geeksquiz") << endl;
    cout << contains("geeksquizgeeks", "quiz") << endl;
    return 0;
}

Output:

1
0
1

Source: http://qa.geeksforgeeks.org/102/recursive-function-implement-functionality-string-substr

This article is contributeed by Bhupinder. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

GATE CS Corner    Company Wise Coding Practice

Recommended Posts:







Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.