Advertisement
Advertisement


Remove last character from C++ string


Question

How can I remove last character from a C++ string?

I tried st = substr(st.length()-1); But it didn't work.

2010/02/22
1
214
2/22/2010 12:56:34 PM

Accepted Answer

For a non-mutating version:

st = myString.substr(0, myString.size()-1);
2010/02/22
197
2/22/2010 12:59:26 PM


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.

2010/02/22

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.

2012/08/01

str.erase( str.end()-1 )

Reference: std::string::erase() prototype 2

no c++11 or c++0x needed.

2014/03/17

That's all you need:

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

if (!st.empty())
    st.pop_back();
2017/12/07

int main () {

  string str1="123";
  string str2 = str1.substr (0,str1.length()-1);

  cout<<str2; // output: 12

  return 0;
}
2010/02/22

Source: https://stackoverflow.com/questions/2310939
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]