
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a String Starts and Ends With Another String in C++
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
#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
Advertisements