从C中的字符串中删除多余的空格 [英] Remove extra whitespace from a string in C

查看:79
本文介绍了从C中的字符串中删除多余的空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个字符串

"go    for    goa" 

并且输出应为

"go for goa"

我要删除多余的空格。这意味着两个或多个连续的空格应替换为一个空格。我想使用就地算法来做到这一点。

I want to remove the extra spaces. That means two or more consecutive spaces should be replaced with one space. I want to do it using an in place algorithm.

下面是我尝试过的代码,但它不起作用:

Below is the code I tried but it doesn't work:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Function to remove spaces in an string array */
char *removeSpaces(char *str) {
  int  ip_ind = 1;
  /* In place removal of duplicate spaces*/
  while(*(str + ip_ind)) {
    if ((*(str + ip_ind) == *(str + ip_ind - 1)) && (*(str + ip_ind)==' ')) {
      *(str_ip_ind-1)= *(str + ip_ind);
    }
    ip_ind++;
  }
  /* After above step add end of string*/
  *(str + ip_ind) = '\0';
  return str;
}
/* Driver program to test removeSpaces */
int main() {
  char str[] = "go   for  go";
  printf("%s", removeSpaces(str));
  getchar();
  return 0;
}


推荐答案

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

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

这篇关于从C中的字符串中删除多余的空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆