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

1. Using pop_back() function

The recommended approach is to use the pop_back() function introduced with C++11 to erase the last character of the string.

Download  Run Code

Output:

C,C++,Java

2. Using resize() function

The string class also provides a resize() function that can be used to resize the string to a particular length.

Download  Run Code

Output:

C,C++,Java

3. Using erase() function

Another efficient solution is to use the erase() function of the string class. It has two variants. We can either:

1. Get the iterator to the last character and call the erase() function.

Download  Run Code

Output:

C,C++,Java

 
2. Pass the last character’s index to the erase() function, which erases the last character.

Download  Run Code

Output:

C,C++,Java

 
Please note that calling the substr() function on the string doesn’t modify the original string but constructs a new string. This can still work, as demonstrated here.

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