简体   繁体   English

使用递归函数反转字符串

[英]Reverse a string using a recursive function

I am currently studying C and I can't get past this exercise. 我目前正在学习C,我无法通过这项练习。 I must create a recursive function to reverse string1 into string2 . 我必须创建一个递归函数来将string1反转为string2 Here is my code. 这是我的代码。 I would gladly appreciate your help. 我很乐意感谢你的帮助。

#include <stdio.h>
#define MAX 100

void reverse(char s1[],char s2[],int n,int j);

int main()
{
    char string1[MAX]="How Are You Mate";
    char string2[MAX]="";
    int n=0;
    int i=0;
    int j=0;

    for(i=0;string1[i]!='\0';i++)
        n++;
    reverse(string1,string2,n,j);
    printf("String-a normal:\n%s\n",string1);
    printf("String-a reverse:\n%s\n",string2);
    return 0;
}

void reverse(char s1[],char s2[],int n,int j)
{
     if(n>0)
     {
            s2[j]=s1[n];
            reverse(s1,s2,n-1,j+1);
     }
     else
            s2[j]='\0';
}

in-place (the caller could make a copy of the string before calling this function) string reverse with tail-recursion 就地(调用者可以在调用此函数之前复制字符串)字符串反向使用尾递归

void reverse (char *str, size_t len)
{
  char tmp;
  if (len-- < 2) return;

  tmp = *str;
  *str = str[len];
  str[len] = tmp;

  reverse (str+1, len -1);
}

O, if you don't want pointers: 哦,如果你不想要指针:

void reverse (char str[], size_t len)
{
  char tmp;
  if (len-- < 2) return;

  tmp = str[0];
  str[0] = str[len];
  str[len] = tmp;

  reverse (str+1, len -1);
}

The reversing starts by copying the n -th character of string1 array into string2 . 通过将string1数组的第n个字符复制到string2开始反转。 The n -th character happens to be the null terminator. n个字符恰好是空终止符。 It becomes the first character of your new string, so the string looks empty to all standard C routines, including printf . 它成为新字符串的第一个字符,因此字符串对于所有标准C例程(包括printf看起来都是空的。

Calling 调用

reverse(string1,string2,n-1,j);

from the main should fix the problem. main应该解决问题。 The condition in the reverse should be changed from if(n>0) to if(n>=0) as well. reverse条件也应该从if(n>0)变为if(n>=0)

Although it does not save the resulting string anywhere, you get the idea. 虽然它不会结果字符串保存在任何地方,但您可以理解。

#include <stdio.h>

void rev (const char* str);

int main () {
    const char str[] = "!dlrow ,olleH";

    printf("%s\n", str);

    rev(str);
    printf("\n");

    return 0;
}

void rev (const char* str) {
    char c = *str;
    if (c != '\0') {
            rev(str + 1);
        printf("%c", c);
    }
}

I have corrected the program. 我已经纠正了这个程序。 Please find the changes below 请在下面找到更改

void reverse(char s1[],char s2[],int n,int j)
{
 if(n>0)
 {
        s2[j]=s1[n-1];
        reverse(s1,s2,--n,++j);
 }
 else
        s2[j]='\0';
}

i recommend using library , size=strlen(array) in stead of 我建议使用library,size = strlen(array)来代替

for(i=0;string1[i]!='\0';i++)
n++;

to count how many characters in arra 计算arra中有多少个字符

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM