Stuck with C syntax
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 str开发者_运维问答ing:
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?
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';
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.
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'?
A slight improvement perhaps:
while(*mypointer == a space) {
*mypointer-- = '\0';
}
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...
精彩评论