我想用 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/