In this article we will discuss both case sensitive and insensitive implementations to check if a string ends with an another given string.

In previous article we discussed different implementations of startsWith() function for std::string. Here on similar lines we will discuss different implementations of endsWith() function.

In c++, std::string class does not provides any endsWith() function to check if a string ends with an another given string. Let’s see how to do that using std::string::compare() and Boost Library.

std::string endWith() using std::string::compare() and std::all_of()

std::string class provides a member function compare() with different overloaded versions. We will use one of its overloaded version i.e.

It accepts a string as argument to match, starting position for match and number of characters to match. If string matches then it returns 0 else returns > 0 or < 0 based on difference in ascii values of first unmatched character.

To check if a main string ends with a given string, we should look into last n characters only for main string, where n is the size of given string. Let’s use std:string::compare() to find the last occurrence of given string from position (Size of Main string – size of given string).

Case sensitive Implementation of endsWith using std::string::compare()

Case sensitive Implementation of endsWith using std::all_of()

 

Case Insensitive Implementation of endsWith using std::all_of()

Check complete example as follows,

Output:

std::string endsWith() using Boost Library

Boost’s algorithm library provides implementation of both case sensitive and insensitive implementation of endsWith() function for string i.e.

Case Sensitive Version :

Case Insensitive Version :

Header File required : <boost/algorithm/string.hpp>

Checkout complete example as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.