Find if a string starts and ends with another given string in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two strings str and corStr. Our task is to find if a string starts and ends with another given string. 

Let’s take an example to understand the problem,

Input: str = “abcprogrammingabc” conStr = “abc”

Output: True

Solution Approach: 

To solve the problem, we need to check if the string starts and ends with the conStr. For this, we will find the length of string and corStr. Then we will check if len(String) > len(conStr), if not return false.
Check if prefix and suffix of size corStr are equal and check they contain corStr or not.

Program to illustrate the working of our solution,

Example

Live Demo

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

bool isPrefSuffPresent(string str, string conStr) {
   
   int size = str.length();
   int consSize = conStr.length();
   if (size < consSize)
   return false;
   return (str.substr(0, consSize).compare(conStr) == 0 && str.substr(size-consSize, consSize).compare(conStr) == 0);
}

int main() {
   
   string str = "abcProgrammingabc";
   string conStr = "abc";
   if (isPrefSuffPresent(str, conStr))
      cout<<"The string starts and ends with another string";
   else
      cout<<"The string does not starts and ends with another string";
   return 0;
}

Output −

The string starts and ends with another string
raja
Published on 22-Jan-2021 18:19:16
Advertisements