10/23/2007

Reversing string in C

There is a example for reversing string in the Section 3.5 of K&R's 'The C Programming Language' . The example code look like this:
void reverse(char s[]) {

char c;
int i, j;

for (i = 0, j = strlen(s) - 1; i < j; ++i, --j) {
c = s[i], s[i] = s[j], s[j] = c;
}
}

But the above code can be improved. There is 'Pointer Version':
void reverse(char *s) {
char *l = s;
char c;

while (*s++)
;
s -= 2;

while (l < s) {
c = *l;
*l++ = *s;
*s-- = c;
}
}

The *strrev* in C standard library implements the same functionality, but generally implements in assembly code.