Click here to Skip to main content
15,891,704 members
Articles / Programming Languages / C#
Tip/Trick

Swap characters in a string

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
2 Nov 2011CPOL 51.4K   2   5
How to swap characters in a string.

Last month I posted an answer on CodeProject to a pretty logical question. I then thought of sharing it as a Tip/Trick.


Problem/Question


How to swap alternate characters of a string?


For example:


Input: "AXBYCZ"


Output: "XAYBZC"


In case the length of string is an odd number, then the last character should maintain its original position as below.


Input: "AXBYCZT"


Output: "XAYBZCT"


Solution Code


C#
string input = "AXBYCZ"; //Sample String
StringBuilder output = new StringBuilder();

char[] characters = input.ToCharArray();

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

Happy to see other logical solutions for this. :)

License

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


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

Comments and Discussions

 
QuestionAnother solution Pin
BhanuPrasadN24-May-18 17:35
BhanuPrasadN24-May-18 17:35 
GeneralThere's no need to copy the string to an array, and you shou... Pin
PIEBALDconsult8-Nov-11 17:45
mvePIEBALDconsult8-Nov-11 17:45 
Generalcool Pin
Liju Sankar2-Nov-11 18:24
Liju Sankar2-Nov-11 18:24 
GeneralRe: Thank you Sangunni. :) Pin
RaisKazi2-Nov-11 19:04
RaisKazi2-Nov-11 19:04 
Generalcool Pin
Liju Sankar2-Nov-11 18:23
Liju Sankar2-Nov-11 18:23 

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.