Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
656 views
in Technique[技术] by (71.8m points)

algorithm - Remove extra whitespace from a string in C

I have this string

"go    for    goa" 

and the output should be

"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) = '';
  return str;
}
/* Driver program to test removeSpaces */
int main() {
  char str[] = "go   for  go";
  printf("%s", removeSpaces(str));
  getchar();
  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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] = '';
}

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
",str);
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...