Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

more efficient way of remove a few characters from the end of a string

Tags:

c++

string

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.

like image 483
packetie Avatar asked Sep 19 '25 12:09

packetie


1 Answers

std::string::erase is what you are looking for.

If you wanted to erase the last n characters, you would do something like:

st.erase(st.length()-n);

But make sure you do proper bounds checking.

like image 199
dwcanillas Avatar answered Sep 21 '25 03:09

dwcanillas