Reverse a string using a recursive function

后端 未结 5 1865
悲哀的现实
悲哀的现实 2021-01-22 09:10

I am currently studying C and I can\'t get past this exercise. I must create a recursive function to reverse string1 into string2. Here is my code. I w

相关标签:
5条回答
  • 2021-01-22 09:41

    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);
    }
    
    0 讨论(0)
  • 2021-01-22 09:47

    The reversing starts by copying the n-th character of string1 array into string2. The n-th character happens to be the null terminator. It becomes the first character of your new string, so the string looks empty to all standard C routines, including printf.

    Calling

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

    from the main should fix the problem. The condition in the reverse should be changed from if(n>0) to if(n>=0) as well.

    0 讨论(0)
  • 2021-01-22 09:59

    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);
        }
    }
    
    0 讨论(0)
  • 2021-01-22 09:59

    i recommend using library , size=strlen(array) in stead of

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

    to count how many characters in arra

    0 讨论(0)
  • 2021-01-22 10:04

    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';
    }
    
    0 讨论(0)
提交回复
热议问题