Remove first character from string in C++
This post will discuss how to remove the first character from a string in C++.
1. Using string::erase
The recommended solution to in-place remove characters from a string is using the string::erase function. The following C++ program demonstrates its usage using range overload:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string str = "ABCD"; str.erase(0, 1); std::cout << str << std::endl; // BCD return 0; } |
The string::erase function is also overloaded to accept an iterator. The iterator should point to the element that needs to be removed from the string.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string str = "ABCD"; str.erase(str.begin()); std::cout << str << std::endl; // BCD return 0; } |
It is recommended to check for an empty string before invoking the string::erase function. Otherwise, the code throws a std::length_error exception for an empty input sequence.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <string> int main() { std::string str = "ABCD"; if (!str.empty()) { str.erase(str.begin()); } std::cout << str << std::endl; // BCD return 0; } |
To remove the first character only if it matches with a certain character, do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string str = "ABCD"; char ch = 'A'; if (str.front() == ch) { str.erase(str.begin()); } std::cout << str << std::endl; // BCD return 0; } |
2. Using string::substr
The string::erase function in-place modifies the string. To get a copy of the original string with its last character removed, use the string::substr function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <string> int main() { std::string str = "ABCD"; std::string s; if (!str.empty()) { s = str.substr(1, str.size() - 1); } std::cout << s << std::endl; // BCD return 0; } |
That’s all about removing the first character 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 :)