How do I remove leading spaces from strings? My code
for(j=0; command[j]==' ';j++);
only seems to ignore them, when I printout the strings the spaces are still there.
This is a discussion on Remove leading spaces/tabs within the C Programming forums, part of the General Programming Boards category; How do I remove leading spaces from strings? My code for(j=0; command[j]==' ';j++); only seems to ignore them, when I ...
How do I remove leading spaces from strings? My code
for(j=0; command[j]==' ';j++);
only seems to ignore them, when I printout the strings the spaces are still there.
Can you post a little more code?...
Code:for(j=strlen(command) - 1; command[j]==' ' && j > 0;j--); command[j + 1] = '\0';
shaik786, I think you are removing the trailing spaces and not the leading...
One way to do this is have an extra pointer that points to the first character after the leading spaces:
Another way is to find the first character after the spaces and then copy the rest of the buffer to the beginning of the buffer (strcpy):Code:int main(void) { char txt[] = " Hello world!\n"; char *ptr = NULL; for(ptr = txt; *ptr == ' '; ptr++) ; printf(ptr); return 0; }
Or use the memmove function:Code:int main(void) { char txt[20]; char *ptr = NULL; strcpy(txt, " Hello world!\n"); for(ptr = txt; *ptr == ' '; ptr++) ; strcpy(txt, ptr); printf(txt); return 0; }
Code:int main(void) { char txt[20]; int len = 0; int i = 0; strcpy(txt, " Hello world!\n"); len = strlen(txt); for(i = 0; txt[i] == ' '; i++) ; memmove(txt, txt + i, len-i+1); printf(txt); return 0; }
Oops, That's right! Thanks for correcting me Monster.![]()