Answer to Question #198601 in C for Lucy

Question #198601

Task 1: Reverse a character string.

Write a function called str_rev() that takes a pointer to a string as input and reverses the string in-place (this change should be reflected in the original string that was passed to the function, not to a copy of the string). No library functions for string reversal should be used. The function should also return a pointer to the reversed string.

Function prototype is given below:

char * str_rev(char * str);


1
Expert's answer
2021-05-25T15:25:53-0400
#include <stdio.h>

void swap(char* a, char* b)
{
    char temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int str_len(char* str)
{
    int len;
    len = 0;
    while(*str++ != 0) { ++len; }
    return len;
}

char* str_rev(char* str)
{
    int i, len;

    len = str_len(str);

    for(i=0; i<len/2; ++i)
    {
        swap(str + i, str + len - i - 1);
    }

    return str;
}

int main()
{
    char* buffer = "String";

    printf("The string after reversing: %s\n", str_rev(buffer));

    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS