从句子之间删除空格。

时间:2015-10-29 06:12:52

标签: c

我有句话,我想删除空格,但我正在阅读文本文件。这是一个单词样本:

the tree hugged the man
there are many trees
where are the bees

所以它应该是:

thetreehuggedtheman
therearemanytrees
wherearethebees

这是我到目前为止所做的:

int main(int argc, char* argv []) {

    int i = 0, line = 6;
    char word[100];

    char const* const fileName = argv[1];
    FILE *file = fopen(fileName,"r");
    while(line--){
        fgets(word, 100, file);
        i++;
        char *wordRev = reverse(word);

        // Remove spaces from string here



    }

    fclose(file);

    return 0;
}

4 个答案:

答案 0 :(得分:3)

使用strtoksprintf即可实现 -

char s[100];                                  // destination string
int i=0;
while(fgets(word, 100, file)!=NULL){          // read from file
    memset(s,'\0',sizeof s);                  // initialize (reset) s in every iteration
     char *token=strtok(word," ");            // tokenize string read from file
     while(token!=NULL){                      // check return of strtok         
          while(s[i]!='\0')i++;                  
          sprintf(&s[i],"%s",token);         // append it in s   
          token=strtok(NULL," ");
      }
    printf("%s\n",s);                         // print s
}

使用fgets控制循环。循环将停靠为fgets return NULL

请注意,s将在每次迭代中被修改,因此如果您希望稍后在程序中使用它,请将修改后的字符串复制到另一个数组。

答案 1 :(得分:2)

为了使其尽可能简单和通用:

void remove_char (char ch, char* dest, const char* source)
{
  while(*source != '\0')
  {
    if(*source != ch)
    {
      *dest = *source;
      dest++;
    }
    source++;
  }

  *dest = '\0';
}

答案 2 :(得分:0)

如果您想要从行中删除空格,您可以随时解析它:

#include <stdio.h>


#define MAXLN 100

void remove_spaces(char line[]);

int main(int argc, char *argv[])
{
    int line = 6;
    char word[MAXLN];

    char const* const filename = argv[1];
    FILE *file = fopen(filename, "r");

    while (line--) {
        fgets(word, MAXLN, file);
        remove_spaces(word);
    }

    return 0;
}

void remove_spaces(char line[])
{
    char no_spaces[MAXLN];
    for (int i=0, j=0; line[i] != '\0'; i++) {
        if (line[i] == ' ') continue;
        no_spaces[j++] = line[i];
    }
    no_spaces[j-1] = '\0'
    printf("%s\n", no_spaces);
}  

答案 3 :(得分:0)

使用穿过数组的简单函数并跳过空格字符。

void rmSpace(char *string)
{
    size_t len = strlen(string) , index = 0;

    for( size_t n = 0 ; n < len ; n++ )
    {
        if( string[n] != ' ' )
        {
            string[index] = string[n];
            index++;
        }
    }
    string[index] = '\0';
}