Check if a string is substring of another
Last Updated : 16 Oct, 2024
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));
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);
Note: The time complexity of in-built functions can differ across different languages.
Similar Reads
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
2 min read
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 sh
15 min read
Check if a string is a subsequence of another string ( using Stacks ) Given a string S, the task is to check if the string target is a subsequence of string S or not, using a Stack. Examples: Input: S = âKOTTAYAMâ, target = âKOTAâOutput: YesExplanation: âKOTAâ is a subsequence of âKOTTAYAMâ. Input: S = âGEEKSFORGEEKSâ, target =âFORFORâOutput: No Approach: Follow the s
9 min read
Check if a given string is sum-string Given a string s, the task is to determine whether it can be classified as a sum-string. A string is a sum-string if it can be split into more than two substring such that, the rightmost substring is equal to the sum of the two substrings immediately before it. This rule must recursively apply to th
14 min read
Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
8 min read
Check if Permutation of Pattern is Substring Given two strings txt and pat having lowercase letters, the task is to check if any permutation of pat is a substring of txt. Examples: Input: txt = "geeks", pat = "eke"Output: trueExplanation: "eek" is a permutation of "eke" which exists in "geeks".Input: txt = "programming", pat = "rain"Output: fa
12 min read