1

Is it possible to reverse a string in place without using strlen, using recursion and with this definition?

void reverse(char *s, int dim);

The only thing I could do was:

void reverse(char *s, int dim)
{
    int a = dim;
    int b = strlen(s) - 1 - dim;

    if ((a - b) <= 0)
        return;

    swap(s[a], s[b]);

    reverse(s, dim - 1);
}

But I would like to do that without using strlen and without defining a similar function. Is it possible?

1
  • 2
    You cannot reverse a range whose length you don't know. (You can perhaps discover the length by ways other than, but equivalent to, strlen, but you'd only do a worse job of it that strlen would.) Commented Jul 19, 2015 at 12:52

1 Answer 1

3

Ciao. Come va?

As for me I would declare the function the following way

char * reverse( char *s, size_t n );

Here is a demonstrative program

#include <stdio.h>

char * reverse( char *s, size_t n )
{
    if ( !( n < 2 ) )
    {
        char c = s[0];
        s[0] = s[n-1];
        s[n-1] = c;
        reverse( s + 1, n - 2 );
    }

    return s;
}    


int main( void )
{
    char s[] = "Hello misiMe";

    puts( s );
    puts( reverse( s , sizeof( s ) - 1 ) );
}    

The program output is

Hello misiMe
eMisim olleH
Sign up to request clarification or add additional context in comments.

1 Comment

Io bene, tu? Sorry, couldn't resist.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.