繁体   English   中英

从字符串中的特定情况中删除空格

[英]Remove a Space from a Specific case in a string

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

希望这有意义

这是我的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;
}

下面的方法

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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