
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find if a string starts and ends with another given 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
- Related Articles
- Check if a string starts with given word in PHP
- Check if a string ends with given word in PHP
- Python - Check whether a string starts and ends with the same character or not
- Check if a String starts with any of the given prefixes in Java
- How to check if a string starts with a specified Prefix string in Golang?
- How to check if a string ends with a specified Suffix string in Golang?
- Return TRUE if the first string starts with a specific second string JavaScript
- Check if string ends with desired character in JavaScript
- How to check if string or a substring of string starts with substring in Python?
- How to check if string or a substring of string ends with suffix in Python?
- Check whether a string ends with some other string - JavaScript
- Check if a string can be formed from another string using given constraints in Python
- Check If a String Can Break Another String in C++
- Check if string contains another string in Swift
- Python Program to check if a string starts with a substring using regex

Advertisements