Click here to Skip to main content
Click here to Skip to main content

Swap characters in a string

, 2 Nov 2011
Rate this:
Please Sign up or sign in to vote.
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

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. Smile | :)

License

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

About the Author

RaisKazi
Technical Lead
United States United States
No Biography provided

Comments and Discussions

 
GeneralThere's no need to copy the string to an array, and you shou... PinmemberPIEBALDconsult8-Nov-11 17:45 
Generalcool PinmemberSangunni2-Nov-11 18:24 
GeneralRe: Thank you Sangunni. :) PinmemberRaisKazi2-Nov-11 19:04 
Generalcool PinmemberSangunni2-Nov-11 18:23 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 2 Nov 2011
Article Copyright 2011 by RaisKazi
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid