The best, (right?), way to trim a char*

N

Nicolas Pavlidis

I don't know the problem but why not use std::string instad of raw char*?
std::string also supports trimming of strings, and there is no overhead of
memory.

Kind regards,
Nicolas
 
J

Julie

Julie said:
This doesn't allocate or move memory, but operates on the source string:

<see previous post>

Bug in TrimRight, should be:

char * TrimRight(char * string)
{
char * end = (string && *string) ? &string[strlen(string)-1] : 0;
while (end && end>=string && isspace(*end))
{
*end = '\0';
--end;
}
return string;
}
 
D

David Hilsee

Julie said:
Julie said:
This doesn't allocate or move memory, but operates on the source string:

<see previous post>

Bug in TrimRight, should be:

char * TrimRight(char * string)
{
char * end = (string && *string) ? &string[strlen(string)-1] : 0;
while (end && end>=string && isspace(*end))
{
*end = '\0';
--end;
}
return string;
}

I don't think your "end >= string" check is portable. IIRC,
less-than/greater-than/etc pointer comparisons are only valid if the pointer
points to something inside the block of memory or one beyond the last
element. If you move the pointer to just before the first element, you
can't expect the comparison to work on all platforms. In practice, it
generally works, though.

For a quick fix, you could remove the >= test and instead insert a break
when end == string, or count the characters overwritten, comparing it
against what strlen() returned so you know when to stop.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top