This post will discuss how to check if a string ends with another string in C++.

1. Using string::compare

The string::compare function compares the value of a string with the specified string and returns a zero status code if both strings are equal. The idea is to compare the last n characters with the given string with string::compare. It can be used as follows:

Download  Run Code

2. Using std::equal

Alternatively, we can use the std::equal standard algorithm to determine if elements in the two ranges are equal. We can use it as follows to compare the last n characters of a string with another string.

Download  Run Code

3. Using Boost

If you’re already using boost library, you can use the boost::algorithm::ends_with function from the header <boost/algorithm/string/predicate.hpp>. The following code example shows invocation for this function:

Download Code

4. Using std::mismatch

The standard library offers the std::mismatch algorithm, which compares the elements in two specified ranges and returns a pair specifying the first position where they differ. We can check if the string ends with a given string using it by iterating backward from the end of both strings.

Download  Run Code

5. Using string::rfind

The string::rfind function searches the string for the last occurrence of the specified string, starting at or before the specified position. It can be used as follows to check if the string ends with the specified string.

Download  Run Code

6. Using string::ends_with

Starting with C++20, std::string finally provides the string::ends_with function, which returns true if the string ends with the specified suffix. This is demonstrated below:

Download Code

That’s all about checking if a string ends with another string in C++.