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:

Download  Run Code

 
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.

Download  Run Code

 
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.

Download  Run Code

 
To remove the first character only if it matches with a certain character, do like:

Download  Run Code

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.

Download  Run Code

That’s all about removing the first character from a string in C++.