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

1. Using string::erase function

The standard solution to in-place erase a substring from a string is using the string::erase function. It modifies the string by deleting the specified range of characters. It takes one or two parameters: the position of the first character to be deleted, and optionally, the number of characters to be deleted. For example:

Download  Run Code

2. Using string::substr function

The substr() function is another function that can be used to remove the last n characters from a string. It returns a copy of a substring of the string, starting from a given position and having a given length. It takes one or two parameters: the position of the first character of the substring, and optionally, the length of the substring. Here’s an example of its usage:

Download  Run Code

 
Unlike string::erase function, the substr() function returns a new string, which preserves the original string and avoids side effects.

3. Using Regular Expressions

We can also use regular expressions to remove the last n characters from a string. To use regular expressions in C++, we need to import the <regex> header file and use its classes and functions. Here is an example:

Download  Run Code

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