dsa-practice/libs/chapter12/reverse_string.cpp

21 lines
453 B
C++

#include "chapter12.hpp"
#include <string.h>
#include <stdlib.h>
/*
Reverse String: Implement a function void reverse( char* str) in C or C++ which reverses
a null-terminated string.
*/
void reverse_str(char *str){
size_t len = strlen(str);
char *tmp = reinterpret_cast<char*>(malloc(len));
strcpy(tmp, str);
for(unsigned int offset = 0; offset < len; ++offset){
str[offset] = tmp[len-offset-1];
}
str[len] = '\0';
free(tmp);
}