ft_strrev — Reverse a String In-Place
Allowed functions: none
Write a function that reverses (in-place) a string. It must return its parameter.
char *ft_strrev(char *str);
Solution
Download ft_strrev.cchar *ft_strrev(char *str) {
int len = 0;
int i = 0;
char tmp;
while (str[len])
len++;
while (i < len / 2) {
tmp = str[i];
str[i] = str[len - 1 - i];
str[len - 1 - i] = tmp;
i++;
}
return str;
}
How It Works
Goal: Reverse a string in-place and return it.
Approach: Swap characters from both ends of the string, moving inward until the pointers meet in the middle.
Step by step:
- Calculate the string length by iterating to the null terminator.
- Loop with index
ifrom0tolen / 2. - On each iteration, swap
str[i]withstr[len - 1 - i]using a temporary variable. - Return the now-reversed string.
Key concept: In-place reversal using a two-index swap technique, requiring only one extra byte of memory (the tmp variable).