简体   繁体   中英

Remove a Space from a Specific case in a string

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;
}

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'; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM