Remove last character from C++ string

Simple solution if you are using C++11. Probably O(1) time as well:

st.pop_back();

That's all you need:

#include <string>  //string::pop_back & string::empty

if (!st.empty())
    st.pop_back();

if (str.size () > 0)  str.resize (str.size () - 1);

An std::erase alternative is good, but I like the "- 1" (whether based on a size or end-iterator) - to me, it helps expresses the intent.

BTW - Is there really no std::string::pop_back ? - seems strange.


For a non-mutating version:

st = myString.substr(0, myString.size()-1);