Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to reverse a string in C

Tags:

c

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;
}
like image 741
Apollo Avatar asked Dec 02 '15 04:12

Apollo


1 Answers

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;
}
like image 170
keithmo Avatar answered Nov 02 '22 19:11

keithmo