Click here to Skip to main content
15,885,546 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Swap characters in a string

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
13 Nov 2011CPOL 8.2K   1   2
Just for fun, using xor-swap, avoiding StringBuilder:string input = "AXBYCZ";char[] output = input.ToCharArray();for (int lo = 0, hi = 1; hi < output.Length; lo += 2, hi += 2){ output[lo] = (char)(output[lo] ^ output[hi]); output[hi] = (char)(output[lo] ^ output[hi]); ...
Just for fun, using xor-swap, avoiding StringBuilder:

C#
string input = "AXBYCZ";
char[] output = input.ToCharArray();

for (int lo = 0, hi = 1; hi < output.Length; lo += 2, hi += 2)
{
  output[lo] = (char)(output[lo] ^ output[hi]);
  output[hi] = (char)(output[lo] ^ output[hi]);
  output[lo] = (char)(output[lo] ^ output[hi]);
}

Console.WriteLine(new string(output));

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReason for my vote of 5 Working Perfect. Pin
RaisKazi8-Nov-11 3:31
RaisKazi8-Nov-11 3:31 
GeneralThis is working perfect. :) Will Vote-5 once it gets public. Pin
RaisKazi8-Nov-11 0:40
RaisKazi8-Nov-11 0:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.