Find if a String ends With the Given Substring in C++
Last Updated :
01 Feb, 2024
You are given two strings. The task is to check if the main string ends with another string in C++.
Example
Input:
mainString = "Hello! Geek";
targetString = "Geek"
Output: Hello! Geek ends with Geek.
We can find if the given string ends with the target string using the following method:
Checking if the Main String ends with the Given Substring
We can use the std::string::compare() method of string to compare the substring at the end of the main string with the given target string. If they match, the string::compare() function will return 0, otherwise, it will return the non-zero values.
C++ Program to Check if String Ends with Another String
The below example demonstrates the use of the compare function to find if a string ends with another string or not.
C++
#include <iostream>
#include <string>
using namespace std;
bool endsWith( const string& fullString,
const string& ending)
{
if (ending.size() > fullString.size())
return false ;
return fullString.compare(fullString.size()
- ending.size(),
ending.size(), ending)
== 0;
}
int main()
{
string str = "Hello! Geek" ;
string targetStr = "Geek" ;
if (endsWith(str, targetStr)) {
cout << str << " ends with " << targetStr << endl;
}
else {
cout << str << " does not end with " << targetStr
<< endl;
}
return 0;
}
|
Output
Hello! Geek ends with Geek
From C++20 or later we can also use the ends_with
function to check if a string ends with another string.
Share your thoughts in the comments
Please Login to comment...