Author Topic: [C] Reverse a string  (Read 1900 times)

0 Members and 1 Guest are viewing this topic.

Offline _moon

  • /dev/null
  • *
  • Posts: 10
  • Cookies: 1
    • View Profile
[C] Reverse a string
« on: January 12, 2012, 12:00:15 am »
I read an interesting article about Guerilla Interview 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.


Code: [Select]
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 :
Quote
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
All those moments will lost in time, like tears in rain.

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: [C] Reverse a string
« Reply #1 on: January 12, 2012, 12:31:54 am »
Code: (python) [Select]
someString = "123"
print someString[::-1]

heh :D

Offline xzid

  • Knight
  • **
  • Posts: 329
  • Cookies: 41
    • View Profile
Re: [C] Reverse a string
« Reply #2 on: January 12, 2012, 01:01:43 am »
Code: (python) [Select]
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

Offline _moon

  • /dev/null
  • *
  • Posts: 10
  • Cookies: 1
    • View Profile
Re: [C] Reverse a string
« Reply #3 on: January 13, 2012, 11:47:09 pm »
Thanks, nice topic.
All those moments will lost in time, like tears in rain.