Remove n characters from start of a string in C++
This post will discuss how to remove n characters from the start of a string in C++.
1. Using string::erase
The standard solution to erase characters from a string is using the string::erase function. It is overloaded to accept the index of the first character to be erased and the number of characters to erase. It can be invoked as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> void removeFirstN(std::string &str, int n) { str.erase(0, n); } int main() { std::string str = "C++20"; int n = 3; removeFirstN(str, n); std::cout << str << std::endl; // 20 return 0; } |
2. Using string::substr
Note that calling the string::erase function on the string modifies the original string. To construct a new string, we can use the string::substr function, as shown below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> std::string extractFirstN(std::string &str, int n) { if (str.length() < n) { return str; } return str.substr(n); } int main() { std::string str = "C++20"; int n = 3; std::string s = extractFirstN(str, n); std::cout << s << std::endl; // 20 return 0; } |
That’s all about removing n characters from the start of 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 :)