The Wayback Machine - https://web.archive.org/web/20241120040345/https://www.geeksforgeeks.org/check-string-substring-another/
Open In App

Check if a string is substring of another

Last Updated : 16 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two strings txt and pat, the task is to find if pat is a substring of txt. If yes, return the index of the first occurrence, else return -1.

Examples : 

Input: txt = “geeksforgeeks”, pat = “eks”
Output: 2
Explanation: String “eks” is present at index 2 and 9, so 2 is the smallest index.

Input: txt = “geeksforgeeks”, pat = “xyz”
Output: -1.
Explanation: There is no occurrence of “xyz” in “geeksforgeeks”

Using nested loops – O(m*n) Time and O(1) Space

The basic idea is to iterate through a loop in the string txt and for every index in the string txt, check whether we can match pat starting from this index. This can be done by running a nested loop for traversing the string pat and checking for each character of pat matches with txt or not. If all character of pat matches then return the starting index of such substring.

C++
// C++ program to check if a string is substring of other
// using nested loops

#include <iostream>
using namespace std;

// Function to find if pat is a substring of txt
int findSubstring(string &txt, string &pat) {
    int n = txt.length();
    int m = pat.length();

    // Iterate through txt
    for (int i = 0; i <= n - m; i++) {

        // Check for substring match
        int j;
        for (j = 0; j < m; j++) {

            // Mismatch found
            if (txt[i + j] != pat[j]) {
                break;
            }
        }

        // If we completed the inner loop, we found a match
        if (j == m) {

            // Return starting index
            return i;
        }
    }
    
    // No match found
    return -1;
}

int main() {
    string txt = "geeksforgeeks";
    string pat = "eks";
    cout << findSubstring(txt, pat);

    return 0;
}
C
// C program to check if a string is substring of other
// using nested loops

#include <stdio.h>
#include <string.h>

// Function to find if pat is a substring of txt
int findSubstring(char *txt, char *pat) {
    int n = strlen(txt);
    int m = strlen(pat);

    // Iterate through txt
    for (int i = 0; i <= n - m; i++) {

        // Check for substring match
        int j;
        for (j = 0; j < m; j++) {

            // Mismatch found
            if (txt[i + j] != pat[j]) {
                break;
            }
        }

        // If we completed the inner loop, we found a match
        if (j == m) {

            // Return starting index
            return i;
        }
    }
    
    // No match found
    return -1;
}

int main() {
    char txt[] = "geeksforgeeks";
    char pat[] = "eks";
    printf("%d", findSubstring(txt, pat));

    return 0;
}
Java
// Java program to check if a string is substring of other
// using nested loops

class GfG {
    
    // Function to find if pat is a substring of txt
    static int findSubstring(String txt, String pat) {
        int n = txt.length();
        int m = pat.length();

        // Iterate through txt
        for (int i = 0; i <= n - m; i++) {

            // Check for substring match
            int j;
            for (j = 0; j < m; j++) {

                // Mismatch found
                if (txt.charAt(i + j) != pat.charAt(j)) {
                    break;
                }
            }

            // If we completed the inner loop, we found a match
            if (j == m) {

                // Return starting index
                return i;
            }
        }

        // No match found
        return -1;
    }

    public static void main(String[] args) {
        String txt = "geeksforgeeks";
        String pat = "eks";
        System.out.println(findSubstring(txt, pat));

    }
}
Python
# Python program to check if a string is a substring of another
# using nested loops

# Function to find if pat is a substring of txt
def findSubstring(txt, pat):
    n = len(txt)
    m = len(pat)

    # Iterate through txt
    for i in range(n - m + 1):

        # Check for substring match
        j = 0
        while j < m and txt[i + j] == pat[j]:
            j += 1
        
        # If we completed the inner loop, we found a match
        if j == m:
            return i

    # No match found
    return -1

if __name__ == "__main__":
    txt = "geeksforgeeks"
    pat = "eks"
    print(findSubstring(txt, pat))
C#
// C# program to check if a string is substring of other
// using nested loops

using System;

class GfG {
  
    // Function to find if pat is a substring of txt
    static int findSubstring(string txt, string pat) {
        int n = txt.Length;
        int m = pat.Length;

        // Iterate through txt
        for (int i = 0; i <= n - m; i++) {
          
            // Check for substring match
            int j;
            for (j = 0; j < m; j++) {
              
                // Mismatch found
                if (txt[i + j] != pat[j]) {
                    break;
                }
            }

            // If we completed the inner loop, we found a match
            if (j == m) {
                
                // Return starting index
                return i;
            }
        }

        // No match found
        return -1;
    }

    static void Main() {
        string txt = "geeksforgeeks";
        string pat = "eks";
        Console.WriteLine(findSubstring(txt, pat));
    }
}
JavaScript
// JavaScript program to check if a string is a substring of another
// using nested loops

// Function to find if pat is a substring of txt
function findSubstring(txt, pat) {
    const n = txt.length;
    const m = pat.length;

    // Iterate through txt
    for (let i = 0; i <= n - m; i++) {

        // Check for substring match
        let j;
        for (j = 0; j < m; j++) {

            // Mismatch found
            if (txt[i + j] !== pat[j]) {
                break;
            }
        }

        // If we completed the inner loop, we found a match
        if (j === m) {

            // Return starting index
            return i;
        }
    }

    // No match found
    return -1;
}

// Driver code
const txt = "geeksforgeeks";
const pat = "eks";
console.log(findSubstring(txt, pat));

Output
2

Time complexity: O(m * n) where m and n are lengths of txt and pat respectively. 
Auxiliary Space: O(1), as no extra space is required.

Using Pattern Searching Algorithms

There are several Pattern Searching Algorithms like KMP Algorithm, Rabin-Karp Algorithm, Aho-Corasick Algorithm, etc. Please refer to Introduction to Pattern Searching to learn more about them.

Using in-built library functions

This approach uses a built-in function to quickly check if pattern is part of text or not. This makes the process simple and efficient.

C++
// C++ program to check if a string is substring of other
// using in-built functions

#include <iostream>
using namespace std;

int main() {
    string txt = "geeksforgeeks";
    string pat = "eks";
    
    // If pat is found, returns the index of first
    // occurrence of pat. Otherwise, returns a special
    // constant value std::string::npos
    size_t idx = txt.find(pat);
  
    if(idx != string::npos)
        cout << idx;
    else
        cout << -1;

    return 0;
}
C
// C program to check if a string is substring of other
// using in-built functions

#include <stdio.h>
#include <string.h>

int main() {
    const char *txt = "geeksforgeeks";
    const char *pat = "eks";
    
    // If pat is found, strstr returns a pointer to the first
    // occurrence of pat in txt. Otherwise, it returns NULL.
    const char *idx = strstr(txt, pat);
    
    if (idx != NULL) {
      
        // Calculate index by subtracting the base address 
        // of txt from result
        printf("%ld", idx - txt);
    }
    else {
        printf("-1");
    }
  
    return 0;
}
Java
// Java program to check if a string is substring of other
// using in-built functions

class GfG {
    public static void main(String[] args) {
        String txt = "geeksforgeeks";
        String pat = "eks";
        
        // If pat is found, returns the index of first
        // occurrence of pat. Otherwise, returns -1
        int idx = txt.indexOf(pat);
      
        if (idx != -1)
            System.out.println(idx);
        else
            System.out.println(-1);
    }
}
Python
# Python program to check if a string is substring of other
# using in-built functions

if __name__ == "__main__":
    txt = "geeksforgeeks"
    pat = "eks"

    # If pat is found, returns the index of first
    # occurrence of pat. Otherwise, returns a special
    # constant value -1
    idx = txt.find(pat)

    print(idx)
C#
// C# program to check if a string is substring of other
// using in-built functions

using System;

class GfG {
    static void Main() {
        string txt = "geeksforgeeks";
        string pat = "eks";
        
        // If pat is found, returns the index of first
        // occurrence of pat. Otherwise, returns a special
        // constant value -1
        int idx = txt.IndexOf(pat);
  
        Console.WriteLine(idx);
    }
}
JavaScript
// JavaScript program to check if a string is substring of other
// using in-built functions

let txt = "geeksforgeeks";
let pat = "eks";

// If pat is found, returns the index of first
// occurrence of pat. Otherwise, returns -1
let idx = txt.indexOf(pat);

console.log(idx);

Output
2

Note: The time complexity of in-built functions can differ across different languages.



Previous Article
Next Article

Similar Reads

Check if the given string is shuffled substring of another string
Given strings str1 and str2. The task is to find if str1 is a substring in the shuffled form of str2 or not. Print "YES" if str1 is a substring in shuffled form of str2 else print "NO". Example Input: str1 = "onetwofour", str2 = "hellofourtwooneworld" Output: YES Explanation: str1 is substring in shuffled form of str2 as str2 = "hello" + "fourtwoon
15 min read
Check if a string can be converted to another given string by removal of a substring
Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print “YES”. Otherwise, print “NO”. Example: Input: S = “abcdef”, T = “abc” Output: YES Explanation: Removing the substring { S[3], â€Ķ, S[5] } mod
7 min read
Check if a string contains an anagram of another string as its substring
Given two strings S1 and S2, the task is to check if S2 contains an anagram of S1 as its substring. Examples: Input: S1 = "ab", S2 = "bbpobac"Output: YesExplanation: String S2 contains anagram "ba" of S1 ("ba"). Input: S1 = "ab", S2 = "cbddaoo"Output: No Approach: Follow the steps below to solve the problem: Initialize two Hashmaps s1hash and s2has
7 min read
Check if a string can be split into two substrings such that one substring is a substring of the other
Given a string S of length N, the task is to check if a string can be split into two substrings, say A and B such that B is a substring of A. If not possible, print No. Otherwise, print Yes. Examples : Input: S = "abcdab"Output: YesExplanation: Considering the two splits to be A="abcd" and B="ab", B is a substring of A. Input: S = "abcd"Output: No
5 min read
Javascript Program To Check If A String Is Substring Of Another
Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :  Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output: -1. Explanation: There is no occurrence of "prac
2 min read
Lexicographically smallest and largest anagrams of a string containing another string as its substring
Given two strings S1 of size N and S2 of size M, the task is to find the lexicographically smallest and the largest anagrams of S1 such that it contains the string S2 as a substring. Examples: Input: S1 = "hheftaabzzdr", S2 = "earth" Output: abdearthfhzz, zzhfearthdba Explanation: The smallest anagram of the given string S1 with S2 as a substring i
13 min read
Length of longest substring to be deleted to make a string equal to another string
Given two strings str1 and str2, where str2 is a subsequence of str1, the task is to find the length of the longest substring of str1 which when removed, makes the strings str2 and str1 equal. Examples: Input: str1 = “programmingbloods”, str2 = “ibloods” Output: 8 Explanation: Substrings to be removed from str1 are [“program”, “ng”]. Therefore, the
9 min read
Count of substrings of a string containing another given string as a substring
Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = “dab”S[1, 2] = “ab”S[1, 3] = “abc”S[0, 3] = “dabc” Input: S = "hshshshs" T = "hs"Output: 25 Approach: The ide
8 min read
Maximum number of times a given string needs to be concatenated to form a substring of another string
Given two strings S1 and S2 of length N and M respectively, the task is to find the maximum value of times the string S2 needs to be concatenated, such that it is a substring of the string S1. Examples: Input: S1 = "ababc", S2 = "ab"Output: 2Explanation: After concatenating S2 exactly twice, the string modifies to "abab". Therefore, string "abab" i
12 min read
Count of substrings of a string containing another given string as a substring | Set 2
Given two strings S and T of length N and M respectively, the task is to count the number of substrings of S that contains the string T in it as a substring. Examples: Input: S = “dabc”, T = “ab”Output: 4Explanation:Substrings of S containing T as a substring are: S[0, 2] = “dab”S[1, 2] = “ab”S[1, 3] = “abc”S[0, 3] = “dabc” Input: S = “hshshshs” T
8 min read
Minimize length of a string by removing occurrences of another string from it as a substring
Given a string S and a string T, the task is to find the minimum possible length to which the string S can be reduced to after removing all possible occurrences of string T as a substring in string S. Examples: Input: S = "aabcbcbd", T = "abc"Output: 2Explanation:Removing the substring {S[1], ..., S[3]} and modifies the remaining string to "abcbd".
8 min read
Find the longest subsequence of a string that is a substring of another string
Given two strings X and Y consisting of N and M characters, the task is to find the longest subsequence of a string X which is a substring of the string Y. Examples: Input: X = "ABCD", Y = "ACDBDCD"Output: ACDExplanation:"ACD" is longest subsequence of X which is substring of Y. Input: X = A, Y = AOutput: A Naive Approach: The simplest approach to
10 min read
Length of smallest substring of a given string which contains another string as subsequence | Set 2
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. Examples: Input: A = "abcdefababaef", B = "abf"Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5. Input: A = "abcdefababaef", B = "aef"Output: 3 Recommended: Please solve it on "PRACT
12 min read
Find length of smallest substring of a given string which contains another string as subsequence
Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. If there are multiple such substrings in A, return the substring that has the smallest starting index. Examples : Input : A = "abcedbaced" B = "bed"Output : "bced"Explanation : The substring A[2 : 5] is the shortest substring that contains the stri
15 min read
Find length of longest subsequence of one string which is substring of another string
Given two strings X and Y. The task is to find the length of the longest subsequence of string X which is a substring in sequence Y. Examples: Input : X = "ABCD", Y = "BACDBDCD" Output : 3 "ACD" is longest subsequence of X which is substring of Y. Input : X = "A", Y = "A" Output : 1Recommended PracticeFind length of longest subsequenceTry It! PRERE
15+ min read
Print all occurrences of a string as a substring in another string
Given two strings, str1 and str2, the task is to print the indices(Consider, indices starting from 0) of the occurrence of str2 in str1. If no such index occurs, print "NONE". Examples: Input : GeeksforGeeks GeeksOutput : 0 8Input : GFG gOutput : NONEApproach 1 (Naive Approach): A simple solution is to check all substrings of a given string one by
12 min read
Check if substring S1 appear after any occurrence of substring S2 in given sentence
Given strings S1, S2 and S, the task is to check if every substring of S which is same as S1 has another substring of S same as S2 before it. It is given that S1 is always present as a substring in the string S. Examples: Input: S1 = "code", S2 = "geek", S = "sxygeeksgcodetecode"Output: TrueExplanation: Substring S2 is present before both the occur
4 min read
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'th substring
Partition given string in such manner that i'th substring is sum of (i-1)'th and (i-2)'nd substring. Examples: Input : "11235813" Output : ["1", "1", "2", "3", "5", "8", "13"] Input : "1111223" Output : ["1", "11", "12", "23"] Input : "1111213" Output : ["11", "1", "12", "13"] Input : "11121114" Output : []Iterate through the given string by pickin
9 min read
Count occurrences of substring X before every occurrence of substring Y in a given string
Given three strings S, X, and Y consisting of N, A, and B characters respectively, the task is to find the number of occurrences of the substring X before every occurrence of the substring Y in the given string S. Examples: Input S = ”abcdefdefabc”, X = ”def”, Y = ”abc”Output: 0 2Explanation:First occurrence of Y(= "abc"): No of occurrences of X(=
6 min read
Longest substring whose any non-empty substring not prefix or suffix of given String
Given a string S of length N, the task is to find the length of the longest substring X of the string S such that: No non-empty substring of X is a prefix of S.No non-empty substring of X is a suffix of S.If no such string is possible, print −1. Examples: Input: S = "abcdefb"Output: 4Explanation: cdef is the substring satisfying the conditions. Inp
5 min read
Minimum removals to make a string concatenation of a substring of 0s followed by a substring of 1s
Given binary string str of length N​​​​, the task is to find the minimum number of characters required to be deleted from the given binary string to make a substring of 0s followed by a substring of 1s. Examples: Input: str = "00101101"Output: 2Explanation: Removing str[2] and str[6] or removing str[3] and str[6] modifies the given binary string to
11 min read
Find if a given string can be represented from a substring by iterating the substring “n” times
Given a string 'str', check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. Examples: Input: str = "abcabcabc" Output: true The given string is 3 times repetition of "abc" Input: str = "abadabad" Output: true The given string is 2 times repetition of "abad" Input: str = "aabaabaabaab" Ou
15+ min read
Minimum substring flips required to convert given binary string to another
Given two binary strings A and B, the task is to find the minimum number of times a substring starting from the first character of A needs to be flipped, i.e. convert 1s to 0s and 0s to 1s, to convert A to B. Examples: Input: A = “0010”, B = “1011”Output; 3Explanation:Step 1: Flip the entire string A. Therefore, A becomes “1101” .Step 2: Flip the s
7 min read
Minimum substring flips required to convert a Binary String to another
Given two binary strings S1 and S2 of size N and M respectively, the task is to find the minimum number of reversal of substrings of equal characters required to convert the string S1 to S2. If it is not possible to convert the string S1 to S2, then print "-1". Examples: Input: S1 = "100001", S2 = "110111"Output: 2Explanation:Initially string S1 =
6 min read
Find all substrings that are anagrams of another substring of the string S
Given a string S, the task is to find all the substrings in the string S which is an anagram of another different substring in the string S. The different substrings mean the substring starts at a different index. Examples: Input: S = "aba"Output: a a ab baExplanation:Following substrings are anagrams of another substring of the string S: "a": Subs
6 min read
Queries to check if string B exists as substring in string A
Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) - 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A). Examples: Input: A = "abababa", B = "aba", q[] = {0, 1
15+ min read
Check if given string is a substring of string formed by repeated concatenation of z to a
Given a string str, the task is to check if string str is a substring of an infinite length string S in which lowercase alphabets are concatenated in reverse order as: S = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba...." Examples: Input: str = "cbaz"Output: YES Explanation:Given string "cbaz" is a valid sub string of S. Input: str = "ywxt
10 min read
Check if a string can be formed from another string using given constraints
Given two strings S1 and S2(all characters are in lower-case). The task is to check if S2 can be formed from S1 using given constraints: 1. Characters of S2 is there in S1 if there are two 'a' in S2, then S1 should have two 'a' also. 2. If any character of S2 is not present in S1, check if the previous two ASCII characters are there in S1. e.g., if
7 min read
Check if a string can be converted to another string by replacing vowels and consonants
Given two strings S1 and S2, you are allowed only to change a character at any position to any vowel if it is a vowel or to a consonant, if it is a consonant. The task is to check if a string S1 can be changed to S2 or S2 can be changed to S1. Examples: Input: S1 = "abcgle", S2 = "ezggli" Output: Yes Change 'a' to 'e', 'b' to 'z', 'c' to 'g' and 'e
6 min read
Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str2 = "cdfdawb", d = 6 Output: No Approach: An appro
9 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg