This post will discuss how to remove the last character from a string in C++.

1. Using string::pop_back function

The simplest and most intuitive way to remove the last character from a string is to use the string::pop_back function. This function removes the last character from the string and reduces its size by one. For example, the following code removes the last character from the string:

Download  Run Code

 
It is recommended to check for an empty string before invoking the string::pop_back function. Otherwise, the code throws a std::out_of_range exception for an empty input sequence.

Download  Run Code

2. Using string::erase function

Another feasible option to erase the last character from a string is using the string::erase function. This function allows us to erase a part of a string by specifying its position and length. It requires an iterator pointing to the element to be removed from the string. It can be used as follows:

Download  Run Code

 
The string::erase function returns an iterator pointing to the first character after the erased characters. We can use this iterator to access or modify other characters in the string. To remove the last character only if it matches with a certain character, do like:

Download  Run Code

 
The string::erase function is more verbose and less intuitive than the string::pop_back function. Therefore, we should use it when we need to remove more than one character or when we need an iterator pointing to the remaining characters.

3. Using string::resize function

The third option to remove the last character from a string is to resize the string using the string::resize function. This function allows us to change the size of a string by adding or removing characters at its end. If the specified length is smaller than the length of the string, the string gets trimmed from the end. For example, the following code removes the last character from the string:

Download  Run Code

4. Using string::substr function

All the above functions in-place modifies the original string. To avoid modifications to the original string, we can use the string::substr function. Here’s what the code would look like:

Download  Run Code

That’s all about removing the last character from a string in C++.