0

Possible Duplicate:
How do I trim leading/trailing whitespace in a standard way?

I need to remove all spaces from the beginning and at the end of the string for instance if my string is

"     hello     world.       "

(without quotes), I need to print

"hello     world."

I tried something like this:

size_t length = strlen (str);
for (newstr = str; *newstr; newstr++, length--) {
    while (isspace (*newstr)) 
        memmove (newstr, newstr + 1, length--);

but it removes all spaces.

How can I fix it?

Community
  • 1
  • 1
user123
  • 3
  • 1
  • Possible duplicate of http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c and http://stackoverflow.com/questions/656542/trim-a-string-in-c – lhf Aug 23 '11 at 00:15
  • See the answer to this SO question: http://stackoverflow.com/questions/122616/painless-way-to-trim-leading-trailing-whitespace-in-c – Nithin Philips Aug 23 '11 at 00:15
  • 2
    Probably not a good idea using a variable called `new` if you _ever_ expect your code may be used in a C++ environment :-) – paxdiablo Aug 23 '11 at 00:22

2 Answers2

6

Skip the spaces at the beginning with a while(isspace(...)), and then memmove the string from the position you reached to the beginning (you can also do the memmove work manually with the classic "trick" of the two pointers, one for read and one for write).

You start from

[ ][ ][H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]
 ^

[ ][ ][H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]
       ^ skipping the two spaces you move your pointer here

... and with a memmove you have...
[H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]

Then, move your pointer at the end of the string (you can help yourself with a strlen), and go backwards until you find a non-space character. Set the character after it to 0, and voilà, you just cut the spaces off the end of your string.

                                     v start from the end of the string
[H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]

... move backwards until you find a non-space character...
                               v
[H][e][l][l][o][ ][W][o][r][l][d][ ][ ][\0]

.... set the character after it to 0 (i.e. '\0')

[H][e][l][l][o][ ][W][o][r][l][d][\0]

... profit!
Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
3

No need to memmove. Just start at the starting point (scan until first nonspace character). Then, work from the back and find the first non-space character. Move ahead one and then replace with a null termination character.

char *s = str;
while(isspace(*s)) ++s;
char *t = str + strlen(str);
while(isspace(*--t));
*++t = '\0';
Foo Bah
  • 25,660
  • 5
  • 55
  • 79