Remove last n characters from a string in C++
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <string> void removeLastN(std::string &str, int n) { // no-const if (str.length() < n) { return ; } str.erase(str.length() - n); } int main() { std::string str = "C++20"; int n = 2; removeLastN(str, n); std::cout << str << ' '; // C++ return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <string> std::string removeLastN(std::string const &str, int n) { if (str.length() < n) { return str; } return str.substr(0, str.length() - n); } int main() { std::string str = "C++20"; int n = 2; str = removeLastN(str, n); std::cout << str << ' '; // C++ return 0; } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
#include <iostream> #include <string> #include <regex> std::string removeLastN(std::string &str, int n) { if (str.length() < n) { return str; } // Create a regular expression pattern that matches any n characters // at the end of the string std::regex pattern(".{" + std::to_string(n) + "}$"); // Remove the last n characters from the string using regex_replace function // with an empty replacement return std::regex_replace(str, pattern, ""); } int main() { std::string str = "C++20"; int n = 2; str = removeLastN(str, n); std::cout << str << ' '; // C++ return 0; } |
That’s all about removing the last n
characters from a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)