Remove leading spaces/tabs

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 ...

  1. #1
    Registered User
    Join Date
    May 2002
    Posts
    3

    Remove leading spaces/tabs

    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.

  2. #2
    Unregistered
    Guest
    Can you post a little more code?...

  3. #3
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    Code:
    for(j=strlen(command) - 1; command[j]==' ' && j > 0;j--);
    command[j + 1] = '\0';

  4. #4
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    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:
    Code:
    int main(void)
    {
    	char txt[] = "    Hello world!\n";
    	char *ptr = NULL;
    
    	for(ptr = txt; *ptr == ' '; ptr++) ;
    
    	printf(ptr);
    	return 0;
    }
    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[20];
    	char *ptr = NULL;
    
    	strcpy(txt, "    Hello world!\n");
    
    	for(ptr = txt; *ptr == ' '; ptr++) ;
    
    	strcpy(txt, ptr);
    	printf(txt);
    
    	return 0;
    }
    Or use the memmove function:
    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;
    }

  5. #5
    Im back! shaik786's Avatar
    Join Date
    Jun 2002
    Location
    Bangalore, India
    Posts
    345
    Oops, That's right! Thanks for correcting me Monster.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Running remove() gets permission denied error...
    By edomingox in forum C Programming
    Replies: 4
    Last Post: 01-11-2009, 12:55 PM
  2. compare function ignoring leading white space
    By mc72 in forum C Programming
    Replies: 5
    Last Post: 11-23-2008, 01:33 PM
  3. randomly remove elements
    By joan in forum C++ Programming
    Replies: 6
    Last Post: 12-06-2006, 01:46 PM
  4. randomly remove elements
    By joan in forum C++ Programming
    Replies: 2
    Last Post: 12-06-2006, 12:22 PM
  5. Removing Leading & Trailing Whitespace
    By EvilGuru in forum C Programming
    Replies: 11
    Last Post: 12-01-2005, 02:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21