0

I made a simple program that remove all spaces from a string but i want is a program to remove space from the start of a string if there is and another program to remove space from the end of a string

Hope this make sense

Here is my c program that remove spaces from all the string giving

#include<stdio.h>


int main()
{
    int i,j=0;
    char str[50];
    printf("Donnez une chaine: ");
    gets(str);

    for(i=0;str[i]!='\0';++i)
    {
        if(str[i]!=' ')
            str[j++]=str[i];
    }

    str[j]='\0';
    printf("\nSans Espace: %s",str);

    return 0;
}
jww
  • 97,681
  • 90
  • 411
  • 885
Zakaria
  • 65
  • 1
  • 3
  • 13
  • its i c and its not a duplicate because that one is not simple i just want a simple one – Zakaria Dec 02 '18 at 12:37
  • 2
    Possible duplicate of [How do I trim leading/trailing whitespace in a standard way?](https://stackoverflow.com/questions/122616/how-do-i-trim-leading-trailing-whitespace-in-a-standard-way) – caverac Dec 02 '18 at 12:38
  • It seems you did the most difficult... For start: skip spaces and then copy as you did for any chars. For end: from the end, skip spaces and set a \0 on the last one. – Déjà vu Dec 02 '18 at 12:39
  • Sorry but i don't understand ? – Zakaria Dec 02 '18 at 12:50

1 Answers1

0

Below approach

  1. First removes the leading white chars.
  2. Then shift the string.
  3. Then removes the trailing white chars.

     char *beg = str;
     char *travel = str;
    
     /*After while loop travel will point to non whitespace char*/
      while(*travel == ' ') travel++;
    
    /*Removes the leading white spaces by shifting chars*/
     while(*beg = *travel){
         beg++;
         travel++;
     }
    
    /* travel will be pointing to \0 char*/
     if(travel != str) {
       travel--;
       beg--;
     }
    
    /*Remove the trailing white chars*/
     while(*travel == ' ' && travel != beg) travel--;
    
    /*Mark the end of the string*/
    if(travel != str) *(travel+1) = '\0';
    
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
  • Im really sorry but i still don't understant could you write it in a exemple code where the user give a string and it remove spaces from the end and the lead so i could understant ? – Zakaria Dec 02 '18 at 13:06
  • `/* travel will be pointing to \0 char*/` Since you are using a post increment in the while loop, wouldn't `travel` point to the `char` after `'\0'`? (Also it can not be the same as `str` because it is at least incremented once) – Osiris Dec 02 '18 at 13:07
  • @fairy remove your code between `gets(str);` and `printf("\nSans Espace: %s",str);` insert my code. Also you should not be using `gets` you should use `fgets` instead. – kiran Biradar Dec 02 '18 at 13:08
  • @fairy Please read the documentations and man pages, this is no place to explain common standard functions. – Osiris Dec 02 '18 at 13:12