Find if a String ends With the Given Substring in C++
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++
// C++ Program to Check if String Ends with Another String #include <iostream> #include <string> using namespace std; // Function to check if a string ends with another string bool endsWith( const string& fullString, const string& ending) { // Check if the ending string is longer than the full // string if (ending.size() > fullString.size()) return false ; // Compare the ending of the full string with the target // ending return fullString.compare(fullString.size() - ending.size(), ending.size(), ending) == 0; } int main() { // Sample strings for demonstration string str = "Hello! Geek" ; string targetStr = "Geek" ; // Check if the string ends with the target string 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.
Contact Us