c - void 函数(不打印)- 使用递归反转字符串

标签 c

我想用 C 语言编写一个递归函数来反转单词。我知道如何打印它,但实际上我不知道如何反转原始单词。 所以,我想编写一个函数来反转单词,使用指针,使用 string.h,但必须为空,不打印,并更改原始单词。函数原型(prototype): 无效反向(字符*字符串); 我能写的是递归的停止项(我不确定它们是否正确);

if(!string) return; // if the string is empty
if(*(string+1)=='\0' return (*string); // if there is only on char in the string
if(*(string+2))=='\0' // if there are only 2 letters In the strings-swap
temp=(*string);
(*string)= * (string+1);
(*string+1)= temp; // I don't know what to do after..

如果大家能向我解释该怎么做,那就太好了。 谢谢。

最佳答案

尾递归的实现:

#include <stdio.h>
#include <string.h>

/* function prototypes */
void reverse(char *string);
void reverseWorker(char *string, int start, int end);

int main(int argc, const char *argv[]) {
  char string[] = "Hello, world.";
  printf("string (original) = %s\n", string);
  /*
  reverse(string);

  Or, to reverse each word in the string...
  */

  char *ptr = strtok(string, " ");
  while(ptr != NULL) {
    reverse(ptr);
    ptr = strtok(NULL, " ");
    if(ptr != NULL)
      *(ptr-1)=' ';
  }

  /* the rest is the same */

  printf("string (reversed) = %s\n", string);
  return 0;
}

void reverse(char *string) {
  reverseWorker(string, 0, strlen(string)-1);
}

void reverseWorker(char *string, int start, int end) {
  /* terminal condition */
  if(start>=end)
    return;
  /* swap */
  char temp = string[start];
  string[start]=string[end];
  string[end]=temp;
  /* recursive step */
  reverseWorker(string,start+1,end-1);
}

关于c - void 函数(不打印)- 使用递归反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27754181/

相关文章:

C语言,如何检查给定输入是字符还是正整数

c - 为什么同样的程序在 linux 2.6.32 中比 2.6.18 慢?

c++ - 函数参数上的分号

谁能告诉我为什么这个无限的 while 循环不能正常工作?

无法加载 pppd 共享库 - undefined symbol g_string_sized_new

c - union 成员如何存储?

c - C 语言的迷宫游戏正在崩溃。可能的内存泄漏。需要帮助 :)

在 Solaris 上,套接字发送/接收可以返回 errno 27 (EFBIG) 吗?

C GTK+空闲函数运行一次

c - fscanf 到链接列表