Stephen Horne
10/13/2008 4:26:00 AM
On Sun, 12 Oct 2008 14:22:01 -0700 (PDT), sarajan82@gmail.com wrote:
>Hi All,
>
>I have a string represented by char* (I do not user string class):
>char *s="abcd";
>
>Assume I want to remove the last two elements of s. What is the
>standard solution for this?
This kind of string manipulation is more C than C++, but there is
still a library for working with these kinds of strings.
#include <cstring>
It's a bad idea to manipulate a string assigned from a literal,
though. That is...
char *s="abcd";
s[2] = 0; // Don't do this!
Instead, use...
char* s = new char [BUFFERSIZE];
std::strncpy (s, "abcd", BUFFERSIZE);
s [2] = 0;
In the above, I cut the string short by writing a new null terminator
to the appropriate character position.
However, this kind of stuff is very error prone, and tends to be a
cause of crashes, memory corruption, security issues and more. It's
very easy to end up reading/writing past the end of your buffers and
so on. Seriously, just use the std::string class - you'll regret it if
you don't.