首页 > 解决方案 > 从字符串中的特定大小写中删除空格

问题描述

我做了一个简单的程序,从字符串中删除所有空格,但我想要一个程序从字符串的开头删除空格(如果有的话)和另一个程序从字符串的末尾删除空格

希望这是有道理的

这是我的 c 程序,它从所有字符串中删除空格

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

标签: ctrimc-strings

解决方案


下面的方法

  1. 首先删除前导的白色字符。
  2. 然后换弦。
  3. 然后删除尾随的白色字符。

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

推荐阅读