Check if a string starts with a specific substring in C++

Hello, guys in this tutorial, we will learn how to check if a string starts with specific substring in C++. In input, we have two strings let say, s1 and s2. We will check if s1 starts with substring s2 or not.

Example 1

s1=codespeedy
s2=code
ouput
true

Example 2

s1=ilikecoding
s2=like
ouput
false


Algorithm

  • We will make function ‘ifStart’ with the boolean return type.
  • ‘ifstart’ function will take strings and length of strings as parameter
  • If the length of substring (s2) is greater than a string (s1)  then return false.
  • Initialize a for loop  from  i=0 to i=s1.length()-1  .String length()  function is used to find the length of the string and return the length of a string.
  • Check for each i if s1[i] is equal to s2[i]. if s1[i] is not equal to s2[i] then return false.
  • At the end of function return true. 

 

C++ Code: Check if a string starts with a specific substring

#include<iostream>
#include<string> 
using namespace std;

bool isStart(string s1,string s2,int l1,int l2)
{
    
    if(l1<l2)      // if length of substring is greater than string then return false
    return false;
    
    
    for(int i=0;i<l2;i++)
    {
        if(s1[i]!=s2[i])  //check if s1[i] is equal to s2[i] if not then return false
        return false;
        
    }
    
     
    
    return true;
}

int main()
{
    string s1;
    string s2;
    
    cout << "Enter string " << endl; 
    cin >>s1 ;  // input string 
    cout << "Enter substring" << endl;
    cin >>s2;   // input substring 
    
    int l1=s1.length(); // l1 assign to length of string s1 (given string).
    int l2=s2.length(); // l2 assign to length of string s2 (substring).
    
   if(isStart(s1,s2,l1,l2))   // isStart return true then print true
   cout << "true" <<endl;
   else
   cout << "false" <<endl;  // isStart return false then print false
   
   return 0;
    
}
Input
s1=ilovemycountry
s2=ilove
Output
true

Input
s1=chennai
s2=nnai
Output
false

Time complexity of this algorithm is O(n).

Also read:

Leave a Reply

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