Reverse a string using a recursive function

后端 未结 5 1864
悲哀的现实
悲哀的现实 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);
    }
    

提交回复
热议问题