views:

649

answers:

4

Hi!

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

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

+3  A: 

For a non-mutating version:

st = myString.substr(0, myString.size()-1);
Matthieu M.
+1  A: 
int main () {

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

  cout<<str2; // output: 12

  return 0;
}
codaddict
A: 
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.

RC
buf[buf.size()-1] = '\0'; doesn't remove anything - it just changes the character that was there to have the value zero. std:;strings can happily contain such characters.
anon
Neil is correct. I probably should have clarified this in my answer. The second option will effectively change the value of the last character so it won't print, but the string length will stay the same. Using erase actually "removes" the last character and will change the size of the string.
RC
@RC It will print, assuming you use something like cout << buf. How it appears will depend on your platform. And you can always clarify by editing your answer.
anon
+2  A: 
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.

Steve314
There is no `std::string::pop_back` in C++03; it's been added in C++0x, though.
James McNellis
OK - thanks. It caused be a bit of confusion - I could swear I've used it, yet it's not there. Maybe I have a non-standard library in some compiler somewhere (between VC++2003, VC++2008, MinGW GCC3 MinGW GCC 4 and Linux GCC 4, you do get a few differences). More likely, I'm just getting confused with other types.
Steve314