Hi!
How can I remove last character from a C++ string?
I tried st = substr(st.length()-1);
But it didn't work.
Hi!
How can I remove last character from a C++ string?
I tried st = substr(st.length()-1);
But it didn't work.
For a non-mutating version:
st = myString.substr(0, myString.size()-1);
int main () {
string str1="123";
string str2 = str1.substr (0,str1.length()-1);
cout<<str2; // output: 12
return 0;
}
buf.erase(buf.size() - 1);
another option is to:
buf[buf.size()-1] = '\0';
Both of these assume you know that the string is not empty. If so, you'll get an out_of_range
exception.
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.