How to swap two strings?

871 views Asked by At

I have two variables I want to switch which are strings. They contain and first and second name.

I wanted to switch them using the least possible amount of lines so that's why I haven't created a third variable.

I tried using a xor swap but an error message says James Adams can't be converted to type long.

Is xor only for integers, if so how do I swap the variables efficiently? Thanks, any ideas appreciated. I'll add the code if that's helpful.

Plutonix has suggested names = names.OrderBy(Function(o) o).ToArray() which works. Thanks. Can anyone explain how it does because I haven't seen this before?

For counter1 = 0 to 5
   For counter2 = counter1 + 1 to 5
       If names(counter1) >                      names(counter2) then

           names = names.OrderBy(Function(o) o).ToArray()
       End if 
   Next 
Next

Please excuse formatting issues or blame Apple.

1

There are 1 answers

6
therealneil On

The "xor swap trick" is defined on integral types. A string is not an integral type, but rather a sequence of such a type.

http://graphics.stanford.edu/~seander/bithacks.html#SwappingValuesXOR

Consider using a temporary variable instead.