The pop_back() function removes the last element from the string.
slice() method to remove the last 3 characters from a string, e.g. const withoutLast3 = str. slice(0, -3); . The slice method will return a new string that doesn't contain the last 3 characters of the original string.
Removing the first and last character In the example above, we removed the first character of a string by changing the starting point of a string to index position 1, then we removed the last character by setting its value to \0 . In C \0 means the ending of a string.
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null. The following declaration and initialization create a string consisting of the word "Hello".
Simple solution if you are using C++11. Probably O(1) time as well:
st.pop_back();
For a non-mutating version:
st = myString.substr(0, myString.size()-1);
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.
buf.erase(buf.size() - 1);
This assumes you know that the string is not empty. If so, you'll get an out_of_range
exception.
str.erase( str.end()-1 )
Reference: std::string::erase() prototype 2
no c++11 or c++0x needed.
That's all you need:
#include <string> //string::pop_back & string::empty
if (!st.empty())
st.pop_back();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With