C Language Programming: In-Place String Reversal Implementation

The following provides two methods: the manual head-tail swap method and the pointer swap method to implement a function that reverses the input string in place (i.e., swapping the head and tail characters sequentially).

Both methods have a time complexity of O(n).

Pointer Swap Method:

#include <stdio.h>

#include <string.h>

// Inversion of string edit by yyh

char* fun(char *str) {

char *left = str, *right = str + strlen(str) – 1, tmp;

while (left < right){

tmp = *right;

*right– = *left;

*left++ = tmp;

}

return str;

}

int main(void) {

char a[] = “m+7lovecyy”;

int i;

fun(a);

for (i = 0; i < strlen(a); i++)

printf(“%c”, a[i]);

return 0;

}

Manual Head-Tail Swap Method:

#include <stdio.h>

#include <string.h>

// Inversion of string edit by yyh

char* fun(char *str) {

int len = strlen(str);

int i;

char tmp;

for (i = 0; i < len / 2; i++) {

tmp = str[len – 1 – i];

str[len – 1 – i] = str[i];

str[i] = tmp;

}

return str;

}

int main(void) {

char a[] = “m+7lovecyy”;

int i;

fun(a);

for (i = 0; i < strlen(a); i++)

printf(“%c”, a[i]);

return 0;

}

The author believes that the first method is more elegant, but it also has a certain level of difficulty. If the problem does not require in-place swapping, then copying the string and assigning it in reverse order to the source string seems to be a simpler choice.

Leave a Comment