this is a frequently used alogrithm called trimminging -- trim left moves all characters to the left to fill up all the spaces to the left of the string. trim right moves the null-terminator to the left until it reaches the first non-white-sace character (spaces and tabs).
To trim left you need to first find the first non-white-space character in the string. For example " Hello", the first character would be 'H'. then move all the rest of the string to the left so that the result is "Hello". You can use either pointers or indexing with loop counters to do that.
Ancient Dragon
Retired & Loving It
30,050 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
>Regardless of whether you are using C or C++, moving the '\0' character
>around isn't the solution. (both languages have library functions for string manipulation)
For C that statement is debatable. For a full trim it might be better to do the whole operation in one swell foop, if strncpy worked like you seem to think. You still end up tagging '\0' on the end after the copy or you'll get garbage. Worse, a lot of people don't want a full trim, but either a right or a left trim. In that case your suggestion is suboptimal across the board for a right trim and undefined for both because the memory regions overlap. You would have to use memmove to avoid undefined behavior. So it looks like here you're completely wrong. ;)
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Moving around chunks of memory using memmove would not be that good an idea. Think of it this way if the string consists of only spaces with just an alphabet at the end. The memmove implementation would move:
(N - 1) + (N - 2) + ... + 1 bytes.
Here is a supposedly humble implementation which would remove the leading junk character specified by the user:
#include <stdio.h>
#include <stdlib.h>
void removeJunk(char *string, char junk)
{
char *p = string;
int trimmed = 0;
do
{
if (*string != junk || trimmed)
{
trimmed = 1;
*p++ = *string;
}
}
while (*string++ != '\0');
}
int main()
{
char testStr[] = " such a lonely day ";
printf("|%s|", testStr);
removeJunk(testStr, ' ');
putchar('\n');
printf("|%s|", testStr);
getchar();
return 0;
}
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
Your algorithm doesn't work either with strings that contain nothing but junk characters. It will do nothing in that case.
Ancient Dragon
Retired & Loving It
30,050 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Think again -- its a do while loop working with C strings (they have a null terminator at the end).
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734