I would like to remove last n characters from a string. I know there is a method called pop_back()
which can remove the last character. I can use it in a loop like the following, but it doesn't feel efficient.
string st("hello world");
for (i=0; i<n; i++) {
st.pop_back();
}
Wonder if there is more efficient alternative. Thanks.
std::string::erase
is what you are looking for.If you wanted to erase the last
n
characters, you would do something like:But make sure you do proper bounds checking.