EvilZone

Programming and Scripting => C - C++ => : _moon January 12, 2012, 12:00:15 AM

: [C] Reverse a string
: _moon January 12, 2012, 12:00:15 AM
I read an interesting article about Guerilla Interview (http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html) this afternoon.. Which prompted me to check if I could still write some half-decent C, like reversing linked lists or detecting loops in a tree, as mentioned in this article.


That didn't go that well :] Anyway, at some point I stumbled upon a nice string reversing function. Some of you may find it interesting.


:
char* rev(char* str) {
        int end = strlen(str) - 1;
        int start = 0;

        while (start < end) {

                str[start] ^= str[end];
                str[end] ^= str[start];
                str[start] ^= str[end];

                ++start;
                --end;

        }

        return str;
}


The logic behind this being :
Let A = x and B = y.

 So,
 A = A XOR B
   then A = x XOR y
             B = y
 B = A XOR B
   then A = x XOR y
             B = (x XOR y) XOR y
                 = x XOR (y XOR y)
                 = x
 A = A XOR B
   then A = (x XOR y) XOR x
               = (y XOR x) XOR x
               = y XOR (x XOR x)
               = y

 now B = x and A = y

Source: http://discuss.fogcreek.com/techInterview/default.asp?cmd=show&ixPost=2077
: Re: [C] Reverse a string
: Kulverstukas January 12, 2012, 12:31:54 AM
: (python)
someString = "123"
print someString[::-1]

heh :D
: Re: [C] Reverse a string
: xzid January 12, 2012, 01:01:43 AM
: (python)
someString = "123"
print someString[::-1]

heh :D

This seems relevant:

http://codegolf.stackexchange.com/questions/2823/shortest-way-to-reverse-a-number/2826

I like the HTML solution, love reading codegolf.stackexchange
: Re: [C] Reverse a string
: _moon January 13, 2012, 11:47:09 PM
Thanks, nice topic.