Is this function the fastest, most optimized way of reversing a string in C? This runs in O(n/2) time. The optimization is that it only iterates through half of the string.
char* str_reverse(char *str, int len)
{
char word[len];
int i;
for (i = 0; i <= len / 2; ++i) {
word[i] = str[len - i - 1];
word[len - i - 1] = str[i];
}
word[len] = '\0';
return word;
}
Maybe something like this?
char *str_reverse_in_place(char *str, int len)
{
char *p1 = str;
char *p2 = str + len - 1;
while (p1 < p2) {
char tmp = *p1;
*p1++ = *p2;
*p2-- = tmp;
}
return str;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With