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

我试图使这个代码递归,但由于某种原因它不起作用。

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 text_r(char *str) { char *dst = str; if(*str=='\0')return ; *dst++ = *str; if (isspace(*str)) { do ++str; while (isspace(*str)); --str; }//Missing brace from orig is this ok? return text_r(str++); } 

没工作。 有任何想法吗?

您的dst指针在递归调用的函数中不是相同的指针,而是将其作为参数传递。

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

为什么你想用递归来做这件事完全超出了我的方式,它只会浪费时间和空间。

也许这个问题可能会对你有所帮助。 它使用正则表达式解决您的问题