tags:

views:

268

answers:

5

I am trying to remove spaces from the end of a char array (string).

This is the pseudo code of what I am doing, but it keeps deleting the whole string:

if(string length - 1 != a space)
    return

Otherwise, it must equal a space, so

while *mypointer-- != a space
//This should loop back to where there is a character.

Outside of the while loop, I now add one to the pointer by doing

mypointer ++;

and then set mypointer '\0' to signal the end of the string.

I am doing something fundamentally wrong inside of my while, but I cannot seem to figure it out. What could it be?

+5  A: 

A little clairvoyance:

while(*mypointer == a space) {
    --mypointer;
}
mypointer[1] = '\0';

Notice that it is == a space not != a space.


Edit: If I were going to write this, I'd probably really use something like:

#include <string.h>
...

char *mypointer = strrchr(string, ' ');
if (mypointer) *mypointer = '\0';
Richard Pennington
You'll want to write the `\0` one byte further, you're overwriting the last non-space character now.
Wim
Very good point. Fixed.
Richard Pennington
don't forget that Very Bad Things may happen if your string is all spaces.
plinth
also char * mpointer = s + strlen(s); and I would put in ' ' not 'a space' just so its clear u dont mean " "
pm100
and i was just going to say what plinth said
pm100
pm100
Richard, `strrchr` will find the last space: consider the strings `"this is a test"`, and `"this "`. The second string has more than one space at the end, somehow SO is not showing it.
Alok
Alok: Great point. My bad.
Richard Pennington
A: 

Without the code we can just guess:

How is mypointer initialized?

Are you sure about the while loop condition? Should it be while 'last character is space'?

Anssi
+1  A: 

You're probably setting mypointer to \0, which sets the pointer to NULL. You need to set mypointer[1] to \0. Also, make sure you do the right thing for the following edge-cases:

  • when a string is all spaces,
  • when string length is 0.
Alok
A: 

A slight improvement perhaps:

while(*mypointer == a space) {
  *mypointer-- = '\0';
}
Soraz
A: 

Have a look at this code that does the exact job to strip spaces from the end of the string...this is from the Snippets archive - it's an educational thing to watch what's going on when stepping through the debugger and very useful collection of C code also...

Hope this helps, Best regards, Tom.

tommieb75