65.9K
CodeProject is changing. Read more.
Home

Swap characters in a string

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (3 votes)

Nov 2, 2011

CPOL
viewsIcon

52293

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