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

8.8k Views Asked by At

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.

3

There are 3 best solutions below

1
On

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.

7
On

string::substr would be a better way to do this. You could do it like this:

st = st.substr(0, st.length()-n);
0
On
#include <iostream>
#include <string>

int main() {
  std::string st = "hello world";
  int n = 5;
  if (int new_size = st.size() - n; new_size >= 0) {
    st.resize(new_size);
  } else {
    st.clear();
  }
  std::cout << "st = " << st << std::endl;
}

Just in case n is too big :)

PS. Variable declaration in if (...) since C++17.