Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last character from C++ string

People also ask

How do I remove the last character of a char?

The pop_back() function removes the last element from the string.

How do I remove the last 3 characters from a 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.

How do you get rid of the first and last character in a string C?

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.

What is the last character of a string in C?

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();