Simple Approach: The idea is to run a loop from start to end and for every index in the given string check whether the sub-string can be formed from that index. This can be done by running a nested loop traversing the given string and in that loop running another loop checking for sub-string from every index. For example, consider there to be a string of length N and a substring of length M. Then run a nested loop, where the outer loop runs from 0 to (N-M) and the inner loop from 0 to M. For very index check if the sub-string traversed by the inner loop is the given sub-string or not.
C++
// C++ program to check if a string is
// substring of other.
#include <bits/stdc++.h>
usingnamespacestd;
// Returns true if s1 is substring of s2
intisSubstring(string s1, string s2)
{
intM = s1.length();
intN = s2.length();
/* A loop to slide pat[] one by one */
for(inti = 0; i <= N - M; i++) {
intj;
/* For current index i, check for
pattern match */
for(j = 0; j < M; j++)
if(s2[i + j] != s1[j])
break;
if(j == M)
returni;
}
return-1;
}
/* Driver code */
intmain()
{
string s1 = "for";
string s2 = "geeksforgeeks";
intres = isSubstring(s1, s2);
if(res == -1)
cout << "Not present";
else
cout << "Present at index "<< res;
return0;
}
Java
// Java program to check if a string is
// substring of other.
classGFG {
// Returns true if s1 is substring of s2
staticintisSubstring(
String s1, String s2)
{
intM = s1.length();
intN = s2.length();
/* A loop to slide pat[] one by one */
for(inti = 0; i <= N - M; i++) {
intj;
/* For current index i, check for
pattern match */
for(j = 0; j < M; j++)
if(s2.charAt(i + j)
!= s1.charAt(j))
break;
if(j == M)
returni;
}
return-1;
}
/* Driver code */
publicstaticvoidmain(String args[])
{
String s1 = "for";
String s2 = "geeksforgeeks";
intres = isSubstring(s1, s2);
if(res == -1)
System.out.println("Not present");
else
System.out.println(
"Present at index "
+ res);
}
}
// This code is contributed by JaideepPyne.
Python3
# Python3 program to check if
# a string is substring of other.
# Returns true if s1 is substring of s2
defisSubstring(s1, s2):
M =len(s1)
N =len(s2)
# A loop to slide pat[] one by one
fori inrange(N -M +1):
# For current index i,
# check for pattern match
forj inrange(M):
if(s2[i +j] !=s1[j]):
break
ifj +1==M :
returni
return-1
# Driver Code
if__name__ =="__main__":
s1 ="for"
s2 ="geeksforgeeks"
res =isSubstring(s1, s2)
ifres ==-1:
print("Not present")
else:
print("Present at index "+str(res))
# This code is contributed by ChitraNayal
C#
// C# program to check if a string is
// substring of other.
usingSystem;
classGFG {
// Returns true if s1 is substring of s2
staticintisSubstring(strings1, strings2)
{
intM = s1.Length;
intN = s2.Length;
/* A loop to slide pat[] one by one */
for(inti = 0; i <= N - M; i++) {
intj;
/* For current index i, check for
pattern match */
for(j = 0; j < M; j++)
if(s2[i + j] != s1[j])
break;
if(j == M)
returni;
}
return-1;
}
/* Driver code */
publicstaticvoidMain()
{
strings1 = "for";
strings2 = "geeksforgeeks";
intres = isSubstring(s1, s2);
if(res == -1)
Console.Write("Not present");
else
Console.Write("Present at index "
+ res);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to check if a
// string is substring of other.
// Returns true if s1 is substring of s2
functionisSubstring($s1, $s2)
{
$M= strlen($s1);
$N= strlen($s2);
// A loop to slide
// pat[] one by one
for($i= 0; $i<= $N- $M; $i++)
{
$j= 0;
// For current index i,
// check for pattern match
for(; $j< $M; $j++)
if($s2[$i+ $j] != $s1[$j])
break;
if($j== $M)
return$i;
}
return-1;
}
// Driver Code
$s1= "for";
$s2= "geeksforgeeks";
$res= isSubstring($s1, $s2);
if($res== -1)
echo"Not present";
else
echo"Present at index ". $res;
// This code is contributed by mits
?>
Javascript
<script>
// JavaScript program to check if a string is
// substring of other.
// Returns true if s1 is substring of s2
functionisSubstring(s1, s2)
{
varM = s1.length;
varN = s2.length;
/* A loop to slide pat[] one by one */
for(vari = 0; i <= N - M; i++) {
varj;
/* For current index i, check for
pattern match */
for(j = 0; j < M; j++)
if(s2[i + j] != s1[j])
break;
if(j == M)
returni;
}
return-1;
}
/* Driver code */
vars1 = "for";
vars2 = "geeksforgeeks";
varres = isSubstring(s1, s2);
if(res == -1)
document.write( "Not present");
else
document.write( "Present at index "+ res);
</script>
Output
Present at index 5
Complexity Analysis:
Time complexity: O(m * n) where m and n are lengths of s1 and s2 respectively. A nested loop is used the outer loop runs from 0 to N-M and the inner loop from 0 to M so the complexity is O(m*n).
Space Complexity: O(1). As no extra space is required.
An efficient solution is to use a O(n) searching algorithm like KMP algorithm, Z algorithm, etc. Language implementations:
An efficient solution would need only one traversal i.e. O(n) on the longer string s1. Here we will start traversing the string s1 and maintain a pointer for string s2 from 0th index.
For each iteration, we compare the current character in s1 and check it with the pointer at s2.
If they match we increment the pointer on s2 by 1. And for every mismatch, we set the pointer back to 0.
Also keep a check when the s2 pointer value is equal to the length of string s2, if true we break and return the value (pointer of string s1 – pointer of string s2)
Works with strings containing duplicate characters.
C++
#include <bits/stdc++.h>
usingnamespacestd;
intSubstr(string s2, string s1)
{
intcounter = 0; // pointing s2
inti = 0;
for(;i<s1.length();i++)
{
if(counter==s2.length())
break;
if(s2[counter]==s1[i])
{
counter++;
}
else
{
// Special case where character preceding the i'th character is duplicate
if(counter > 0)
{
i -= counter;
}
counter = 0;
}
}
returncounter < s2.length()?-1:i-counter;
}
// Driver code
intmain()
{
string s1 = "geeksforgeeks";
cout << Substr("for", s1);
return0;
}
// this code is contributed by Manu Pathria
Java
importjava.io.*;
classGFG {
publicstaticintSubstr(String s2, String s1){
intcounter = 0; //pointing s2
inti = 0;
for(;i<s1.length();i++){
if(counter==s2.length())
break;
if(s2.charAt(counter)==s1.charAt(i)){
counter++;
}else{
//Special case where character preceding the i'th character is duplicate
if(counter>0){
i -= counter;
}
counter = 0;
}
}
returncounter < s2.length()?-1:i-counter;
}
publicstaticvoidmain (String[] args) {
String s1 = "geeksforgeeks";
//System.out.println(s2.indexOf("for"));
System.out.println(Substr("for", s1));
}
}
Python3
# Python program for the above approach
defSubstr(s1, s2):
counter =0
i =0
Len=len(s1)
while(i < Len):
if(counter ==len(s2)):
break;
if(s2[counter] ==s1[i]):
counter +=1
else:
if(counter > 0):
i -=counter
counter =0
i +=1
if(counter < len(s2)):
return-1
else:
return(i -counter)
# Driver code
print(Substr("geeksforgeeks", "for"))
# This code is contributed by avanitrachhadiya2155
C#
// C# program for the above approach
usingSystem;
classGFG {
staticintSubstr(strings2, strings1)
{
intcounter = 0; // pointing s2
inti = 0;
for(; i < s1.Length; i++) {
if(counter == s2.Length)
break;
if(s2[counter] == s1[i]) {
counter++;
}
else{
// Special case where character preceding
// the i'th character is duplicate
if(counter > 0) {
i -= counter;
}
counter = 0;
}
}
returncounter < s2.Length ? -1 : i - counter;
}
// Driver code
publicstaticintMain()
{
strings1 = "geeksforgeeks";
Console.Write(Substr("for", s1));
return0;
}
}
// This code is contributed by Taranpreet
Javascript
<!-- Javascript program forthe above approach -->
<script>
functionSubstr( s2, s1){
varcounter = 0; // pointing s2
vari = 0;
for( ;i < s1.length; i++)
{
if( counter == s2.length )
{
break;
}
if( s2[counter] == s1[i] )
{
counter++;
}
else
{
// Special case where character preceding
// the i'th character is duplicate
if(counter > 0)
{
i -= counter;
}
counter = 0;
}
}
returncounter < s2.length ? -1 : i-counter;
}
// Driver code
vars1 = "geeksforgeeks";
document.write(Substr("for", s1));
</script>
<!-- thiscode is contributed by Nirajgusain5 -->
Output
5
Complexity Analysis: The complexity of the above code will be still O(n*m) in the worst case and the space complexity is O(1).
Using Library Methods Modern programming languages typically have inbuilt library methods that check if one string is present in another, and the index at which it is located. For instance, the std::find from C++ STL, the index method in Python, the indexOf method in Java, the indexOf method in JavaScript.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy