Monday, 4 July 2016

Reverse a String

First Solution

void reverseString(char* str) { int len, loop;
char temp; len = strlen(str); for(loop = 0; loop < (len / 2); loop++) { temp = str[loop];
str[loop] = str[len - loop - 1];
str[len - loop - 1] = temp; } }

Second Solution

The second solution is slightly better than the first as it does not need the char space. It uses bit manipulation (XOR in this case) to swap the chars in place.

void reverseStringBetter(char* str) { int loop1 = 0, loop2; loop2 = strlen(str) - 1; for (loop1 = 0; loop1 < loop2; loop1++, loop2--) { str[loop1] ^= str[loop2] ; str[loop2] ^= str[loop1] ; str[loop1] ^= str[loop2] ; } }

No comments:

Post a Comment