将多个空格更改为一个空格的递归forms

可能重复:
我试图使这个代码递归,但由于某种原因它不起作用

我试图使用RECURSION编写程序来将多个空格更改为一个空格,任何人都可以帮忙吗? 示例“a_______b”更改为“a_b”这是我尝试做了很长时间的任务! 有人可以帮忙吗?

在这里我尝试了这个,但我认为设计不适用于递归

void text_r(char *str) { char *dst = str; if(*str=='\0')return ; *dst++ = *str; if (isspace(*str)) { do ++str; while (isspace(*str)); --str; } return text_r(str++); } 

我写了没有递归的代码,但我有转换它的问题

void compress_spaces(char * str){char * dst = str;

  for (; *str; ++str) { *dst++ = *str; if (isspace(*str)) { do ++str; while (isspace(*str)); --str; } } *dst = 0; 

}

递归版本(避免任何迭代部分,如同)使用相同的指针,给出两次参数

 void recur(char *str, char *out) { if (*str!=' ' || str[1]!=' ') *out++ = *str; if (*str) recur(str+1, out); } 

只有一个参数的递归版本

 void recur(char *str) { static char *out = NULL; if (out == NULL) out = str; if (*str!=' ' || str[1]!=' ') *out++ = *str; if (*str) recur(str+1); } 

迭代版

 void iter(char *str) { char *out = str; do { if (*str!=' ' || str[1]!=' ') *out++ = *str; } while (*str++); } 

被称为

  char str[] = " abc def "; // either recursive recur(str, str); // or iterative iter(str); 

不是最好的方法,但尝试沿着这些方向

 char* remove_space(char *str) { char *dst = str; while(*str!=' ' ||*str !='\0') *dst++ = *str; if (isspace(*str)) { do ++str; while (isspace(*str)); --str; } return strcat(dst,remove_space(str++)); } 

想法是你找到字符并将它们存储在一个字符串中,当你到达一个空间时,你存储第一个字符并忽略其余部分。 然后,您可以再次将新字符串发送到该函数。 然后返回用新字符串连接的结果

PS可能上面的代码不会编译,但它应该让你知道如何处理它。

详细说明:

创建一个将所有字符保存到空格的函数,然后忽略所有连续的空格,并将剩余的字符串发送给返回干净字符串的函数。 然后它连接两个字符串以制作更大的干净字符串。

这是我的实施。 我通过保留最后一个空格字符来替换多个空格的每个波段,并在找到非空格字符时删除该波段

 void reduce(String s, int curIndex, int lastSpaceIndex) if (lastSpaceIndex != -1) if s[curIndex] is not a space then replace substring from s[lastSpaceIndex, curIndex-1] by a space else reduce(s, curIndex+1, lastSpaceIndex); else if s[curIndex] is not a space then reduce(s, curIndex+1, -1) else reduce(s, curIndex+1, curIndex)