как объединить все возможные пробелы в тексте на С - PullRequest
0 голосов
/ 24 сентября 2019

Цель функции - объединить все возможные пробелы в строке в один пробел.Код, который я написал, работает, за исключением одной строки, где он разрывается.

void merge_whitespace(char *str) {
     char *d = str;

  while(*str != '\0') {
        while (*str == '\t' || *str == '\r' || *str == '\n' || *str =='\f' || *str =='\v' || (*str == ' ' && *(str+1) == ' ')) {
          str++;
        }
      *d++ = *str++;
  }
    *d = '\0';
 }   


test
[This  is another test.     Now we 

 have all kinds of    white space   ]

My output is:
[This is another test. Now we  have all kinds of white space ]


but should be:

[This is another test. Now we have all kinds of white space ]

So the problem is in the string test, it prints two spaces instead of one.

1 Ответ

1 голос
/ 24 сентября 2019

Текст выглядит как

" \n "

Итак, когда встречается 1-й пробел, он проверяет, что

(*str == ' ' && *(str+1) == ' ')

str действительно равно '', но str + 1 равно '\ n', а не' '.Итак, вот как это терпит неудачу.

...