Thursday, July 30, 2009

How do you delete the last element of a string in C++?

If you actually mean a C++ string object, then the above answer is the best way to handle it.





If you really mean a classic C string (null-terminated character array), the easiest and fastest way to "remove" the last character of such a string is to put another, earlier null terminator in that last non-null position:





----------------


s1[strlen(s1) - 1] = '\0';


----------------





(Yes, I know that the first solution works for a classic C string too through the magic of copy constructors and conversion operators. However, in this particular case, implicit use of the string object functions is both more complicated and less efficient than the C-only solution.)

How do you delete the last element of a string in C++?
s1 = s1.substr(0, s1.length() - 1);


No comments:

Post a Comment