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

Tagged as

Swap characters in a string

, 2 Nov 2011 CPOL
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.


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]);

Happy to see other logical solutions for this. Smile | :)


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


About the Author

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 18:45 
Generalcool PinmemberSangunni2-Nov-11 19:24 
GeneralRe: Thank you Sangunni. :) PinmemberRaisKazi2-Nov-11 20:04 
Generalcool PinmemberSangunni2-Nov-11 19: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 | Terms of Use | Mobile
Web01 | 2.8.1411028.1 | Last Updated 2 Nov 2011
Article Copyright 2011 by RaisKazi
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid