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);
#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;
}
Comments
Leave a comment