Write a recursive version of the function reverse(s), which reverses the string s in place.
I'm studying K&R and wrote a code for the question.
void reverse(char s[], int n) // The seconde argument should be always 1.
{ // The function should be always called as reverse(s, 1);
int temp;
int len;
len = strlen(s);
if ((len + 1) / 2 > n)
reverse(s, n + 1);
temp = s[n-1];
s[n-1] = s[(len - 1) - (n-1)];
s[(len - 1) - (n-1)] = temp;
}
The second argument n
says reverse() is currently called at n-th times. The function works as if it sets an axis of symmetry at s[(strlen(s) + 1) / 2]
(since integer division is truncated, it's not always symmetric by the axis but the function behaves as if truncation doesn't happen and it is exactly an symmetric axis) and accordingly change s[n - 1]
with s[(strlen(s) - 1) - (n - 1)]
and vice versa. The function stops its recursive call when the index of the axis is larger than n.
I saw other solutions(this and this). I think they used nice idea for the question. But I wonder how you think about mine. Thanks for reading!