Click here to Skip to main content
15,885,758 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 (3 votes)
3 Nov 2011CPOL 11.9K   1   4
Can't this be done with a simple for loop followed by a single if statement?for(int i=0;i<characters.Length-1;i+=2){ output.Append(characters[i+1]); output.Append(characters[i]);}if (characters.Length % 2 == 1) output.Append(characters[characters.Length - 1]);

Can't this be done with a simple for loop followed by a single if statement?


C#
for(int i=0;i<characters.Length-1;i+=2)
{
    output.Append(characters[i+1]);
    output.Append(characters[i]);
}

if (characters.Length % 2 == 1) output.Append(characters[characters.Length - 1]);

License

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


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

Comments and Discussions

 
GeneralOh, no... now I want to write one that uses Reflection to al... Pin
PIEBALDconsult8-Nov-11 17:58
mvePIEBALDconsult8-Nov-11 17:58 
GeneralSlightly different, taking advantage of some binary operator... Pin
Luc Pattyn5-Nov-11 13:22
sitebuilderLuc Pattyn5-Nov-11 13:22 
GeneralReason for my vote of 5 Working as expected. Pin
RaisKazi3-Nov-11 20:38
RaisKazi3-Nov-11 20:38 
GeneralYep, That's working Great! Here you get my 5 for this. I hop... Pin
RaisKazi3-Nov-11 20:38
RaisKazi3-Nov-11 20:38 

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.