Find a Sub-string in a given String in C++

In this tutorial, we will learn how to find a Sub-string in a given String using C++. Finding a Sub-string in C++ is very much easy if you follow the below steps.

This program prints ” Sub-string Found” if the sub-string is present in the given string, otherwise “Sub-string not Found” as an output.

Methods to find a Sub-string in C++

There are many possible ways to solve this question with different methods. Here we discuss two important approaches to solve this question.

Method 1 :

This is the direct method to solve the problem is to go through all the indices of a given string and check whether a given string is present or not.

we should consider two strings “str1” and “str2”, where “str1” represents the given string and “str2” represents the sub-string.

 Code Snippet :

#include <bits/stdc++.h>
using namespace std;

int main() 
{
        int c=0,j=0,i;
        string str1,str2;
        cout<<"Enter the string\n";
        cin>>str1;
        cout<<"Enter the sub-string\n";
        cin>>str2;
        for(i=0;i<str1.length()-str2.length()+1;i++)
        {
           //checking first character of both strings are equal or not
           if(str1[i]==str2[j]) 
           {
             c=1;
             for(j=1;j<str2.length();j++) 
           //checking remaining characters of both strings are equal or not
               if(str1[j+i]==str2[j]) 
                  c++;
                    j=0;
           }
           // if count(c) equals to length of second string then sub-string is found
           if(c==str2.length()) 
           {
              cout<<"Sub-string Found\n";
              break;
           }
        }
         // if value of i reaches end of loop then sub-string is not found
        if(i==(str1.length()-str2.length()+1))  
          cout<<"Sub-string not Found\n";
        return 0;
}

Input :




Enter the string
codespeedy
Enter the sub-string
speed

Output :

Sub-string Found

Also, read:

 

Method 2 :

In this method, we will use std::find whether a sub-string is present in a given string or not.

It returns an Iterator to the first element in a range that compares equal to the given value.

If no such element found, the function returns the last.

Code Snippet :

#include <bits/stdc++.h>
using namespace std;
int main() 
{
  string str1,str2;
  cout<<"Enter the String\n";
  cin>>str1;
  cout<<"Enter the Sub-string\n";
  cin>>str2;
  // It returns first if given value is present, otherwise last.
  if(str1.find(str2)!=std::string::npos) 
      cout<<"Sub-string Found\n";
  else
      cout<<"Sub-string not Found\n";
  return 0;
}

Input :

Enter the String
codespeedy
Enter the Sub-string
speed

Output :

Sub-string Found

We hope this tutorial helped you to find a sub-string in a given string in c++.


Leave a Reply

Your email address will not be published. Required fields are marked *