且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从C中的字符串中删除多余的空格

更新时间:2022-02-24 22:42:57

大多数解决方案看上去都不必要地复杂:

Most solutions seem needlessly complicated:

#include <ctype.h>
#include <stdio.h>

void strip_extra_spaces(char* str) {
  int i, x;
  for(i=x=0; str[i]; ++i)
    if(!isspace(str[i]) || (i > 0 && !isspace(str[i-1])))
      str[x++] = str[i];
  str[x] = '\0';
}

int main(int argc, char* argv[]) {
  char str[] = "  If  you  gaze   into  the abyss,    the   abyss gazes also   into you.    ";
  strip_extra_spaces(str);
  printf("%s\n",str);
  return 0;
}