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

标签 c

我正在尝试使此代码递归,但由于某种原因它不起作用。

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

顺便说一下,为什么你想用递归来做到这一点,我完全无法理解,它只会浪费时间和空间。

关于c - 我试图使这段代码递归,但由于某种原因它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14702016/

相关文章:

c++ - 如何将双引号放入字符串文字中?

c - Protobuf-C 编译问题

c - 声明和定义

c - %c 在 GCC 内联汇编代码中是什么意思?

c - 使用数组作为函数参数

c - 在 C 中始终为静态函数提供函数原型(prototype)是一种好习惯吗?

c - C 中的段错误

c - GLFW3 错误 - "WGL: Failed to find a suitable pixel format"

c++ - 在 C/C++ 中列出项目的最有效方法

c - 需要透明类型的好处和情况是什么?