Open In App
Related Articles

Recursive function to do substring search

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 the current character is the last character of the text, but pat
       has more characters, return false.

    2) Else If the current character is the last character of the 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 the implementation of the above algorithm. 

C++

// 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 characters of pat and text match
 if (*text == *pat)
  if(exactMatch(text, pat))
   return 1;
  else
  return contains(text + 1, pat);
 
 // If current characters 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;
}

                    

Java

// Recursive Java program to find if a given pattern is
// present in a text
 
class GFG {
    static int exactMatch(String text, String pat, int text_index, int pat_index) {
        if (text_index == text.length() && pat_index != pat.length())
            return 0;
 
        // Else If last character of pattern reaches
        if (pat_index == pat.length())
            return 1;
 
        if (text.charAt(text_index) == pat.charAt(pat_index))
            return exactMatch(text, pat, text_index + 1, pat_index + 1);
 
        return 0;
    }
 
    // This function returns true if 'text' contain 'pat'
    static int contains(String text, String pat, int text_index, int pat_index) {
        // If last character of text reaches
        if (text_index == text.length())
            return 0;
 
        // If current characters of pat and text match
        if (text.charAt(text_index) == pat.charAt(pat_index)) {
            if (exactMatch(text, pat, text_index, pat_index) == 1)
                return 1;
            else
                return contains(text, pat, text_index + 1, pat_index);
        }
 
        // If current characters of pat and tex don't match
        return contains(text, pat, text_index + 1, pat_index);
    }
 
    // Driver program to test the above function
    public static void main(String args[]) {
        System.out.println(contains("geeksforgeeks", "geeks", 0, 0));
        System.out.println(contains("geeksforgeeks", "geeksquiz", 0, 0));
        System.out.println(contains("geeksquizgeeks", "quiz", 0, 0));
 
    }
}
// This code is contributed by Saurabh Jaiswal

                    

Python3

# Recursive Python3 program to find if a given pattern is
# present in a text
 
def exactMatch(text, pat, text_index, pat_index):
    if text_index == len(text) and pat_index != len(pat):
        return 0
  
    # Else If last character of pattern reaches
    if pat_index == len(pat):
        return 1
  
    if text[text_index] == pat[pat_index]:
        return exactMatch(text, pat, text_index+1, pat_index+1)
  
    return 0
 
  
# This function returns true if 'text' contain 'pat'
def contains(text, pat, text_index, pat_index):
    # If last character of text reaches
    if text_index == len(text):
        return 0
  
    # If current characters of pat and text match
    if text[text_index] == pat[pat_index]:
        if exactMatch(text, pat, text_index, pat_index):
            return 1
        else:
            return contains(text, pat, text_index+1, pat_index)
  
    # If current characters of pat and tex don't match
    return contains(text , pat, text_index+1, pat_index)
  
# Driver program to test the above function
 
print(contains("geeksforgeeks", "geeks", 0, 0))
print(contains("geeksforgeeks", "geeksquiz", 0, 0))
print(contains("geeksquizgeeks", "quiz", 0, 0))
 
# This code is contributed by ankush_953.

                    

C#

// Include namespace system
using System;
 
 
// Recursive C# program to find if a given pattern is
// present in a text
public class GFG
{
    public static int exactMatch(String text, String pat, int text_index, int pat_index)
    {
        if (text_index == text.Length && pat_index != pat.Length)
        {
            return 0;
        }
        // Else If last character of pattern reaches
        if (pat_index == pat.Length)
        {
            return 1;
        }
        if (text[text_index] == pat[pat_index])
        {
            return GFG.exactMatch(text, pat, text_index + 1, pat_index + 1);
        }
        return 0;
    }
    // This function returns true if 'text' contain 'pat'
    public static int contains(String text, String pat, int text_index, int pat_index)
    {
        // If last character of text reaches
        if (text_index == text.Length)
        {
            return 0;
        }
        // If current characters of pat and text match
        if (text[text_index] == pat[pat_index])
        {
            if (GFG.exactMatch(text, pat, text_index, pat_index) == 1)
            {
                return 1;
            }
            else
            {
                return GFG.contains(text, pat, text_index + 1, pat_index);
            }
        }
        // If current characters of pat and tex don't match
        return GFG.contains(text, pat, text_index + 1, pat_index);
    }
    // Driver program to test the above function
    public static void Main(String[] args)
    {
        Console.WriteLine(GFG.contains("geeksforgeeks", "geeks", 0, 0));
        Console.WriteLine(GFG.contains("geeksforgeeks", "geeksquiz", 0, 0));
        Console.WriteLine(GFG.contains("geeksquizgeeks", "quiz", 0, 0));
    }
}

                    

Javascript

<script>
 
// Recursive JavaScript program to find if a given pattern is
// present in a text
 
function exactMatch(text, pat, text_index, pat_index){
    if(text_index == text.length && pat_index != pat.length)
        return 0
  
    // Else If last character of pattern reaches
    if(pat_index == pat.length)
        return 1
  
    if(text[text_index] == pat[pat_index])
        return exactMatch(text, pat, text_index+1, pat_index+1)
  
    return 0
}
 
  
// This function returns true if 'text' contain 'pat'
function contains(text, pat, text_index, pat_index){
    // If last character of text reaches
    if(text_index == text.length)
        return 0
  
    // If current characters of pat and text match
    if(text[text_index] == pat[pat_index]){
        if(exactMatch(text, pat, text_index, pat_index))
            return 1
        else
            return contains(text, pat, text_index+1, pat_index)
    }
  
    // If current characters of pat and tex don't match
    return contains(text , pat, text_index+1, pat_index)
}
  
// Driver program to test the above function
 
document.write(contains("geeksforgeeks", "geeks", 0, 0),"</br>")
document.write(contains("geeksforgeeks", "geeksquiz", 0, 0),"</br>")
document.write(contains("geeksquizgeeks", "quiz", 0, 0),"</br>")
 
// This code is contributed by shinjanpatra.
 
</script>

                    

Output:

1
0
1

Time Complexity : O(n*m)
Auxiliary Space : O(n+m)

Java

public class Main {
    // Function to search for a string in another string
    public static boolean str_search(String st, String text,
                                     int k)
    {
        int n = st.length(); // length of the string to
                             // search in
        int m = text.length(); // length of the string to
                               // search for
        if (k
            < n - m + 1) { // if the search index is within
                           // the bounds of the string
            if (st.substring(k, k + m).equals(
                    text)) { // if the substring matches the
                             // search string
                return true; // return true
            }
            else { // if the substring does not match the
                   // search string
                return str_search(
                    st, text,
                    k + 1); // recursively call the function
                            // with the next index
            }
        }
        else { // if the search index is out of bounds
            return false; // return false
        }
    }
 
    public static void main(String[] args)
    {
        String t = "this is a test text"; // the string to
                                          // search in
        System.out.println(str_search(
            t, "test",
            0)); // call the function and print the result
    }
}

                    

Python3

def str_search(st, text, k):
    n = len(st)
    m = len(text)
    if k < n-m+1:
        if st[k:k+m] == text:
            return True
        else:
            return str_search(st, text, k+1)
 
    else:
        return False
 
 
t = 'this is a test text'
print(str_search(t, 'test', 0))

                    

C#

using System;
 
class MainClass {
 
    // Function to search for a string in another string
    public static bool StrSearch(string st, string text, int k) {
        int n = st.Length; // length of the string to search in
        int m = text.Length; // length of the string to search for
 
        if (k < n - m + 1) { // if the search index is within the bounds of the string
            if (st.Substring(k, m).Equals(text)) { // if the substring matches the search string
                return true; // return true
            } else { // if the substring does not match the search string
                return StrSearch(st, text, k + 1); // recursively call the function with the next index
            }
        } else { // if the search index is out of bounds
            return false; // return false
        }
    }
 
    static void Main() {
        string t = "this is a test text"; // the string to search in
        Console.WriteLine(StrSearch(t, "test", 0)); // call the function and print the result
    }
}

                    

Javascript

// Javascript proggram for the above approach
 
function str_search(st, text, k) {
    let n = st.length;
    let m = text.length;
    if (k < n - m + 1) {
        if (st.substring(k, k + m) === text) {
            return true;
        } else {
            return str_search(st, text, k + 1);
        }
    } else {
        return false;
    }
}
 
let t = 'this is a test text';
console.log(str_search(t, 'test', 0));
 
// This code is contributed by princekumaras

                    

C++14

#include <iostream>
#include <string>
 
using namespace std;
 
// Function to search for a string in another string
bool str_search(string st, string text, int k)
{
    int n = st.length(); // length of the string to search in
    int m = text.length(); // length of the string to search for
    if (k < n - m + 1) // if the search index is within the bounds of the string
    {
        if (st.substr(k, m) == text) // if the substring matches the search string
        {
            return true; // return true
        }
        else // if the substring does not match the search string
        {
            return str_search(st, text, k + 1); // recursively call the function with the next index
        }
    }
    else // if the search index is out of bounds
    {
        return false; // return false
    }
}
 
int main()
{
    string t = "this is a test text"; // the string to search in
    if(str_search(t, "test", 0))
        cout<<"true"<< endl;
    else
        cout<<"false"<<endl;// call the function and print the result
    return 0;
}

                    

Output
True

Time Complexity : O((n-m+1)*m), where n is the length of the string to search in and m is the length of the string to search for.

Auxiliary Space : O(m), because the only additional memory used is the substring of length m that is created for each recursive call.



Last Updated : 06 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads