Click here to Skip to main content
12,944,475 members (52,850 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


1 bookmarked
Posted 2 Nov 2011

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


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
Full Stack Technology Professional

Hands-on experience with -
. Asp.Net, MVC, C#, Ajax
. JavaScript, Jquery, AngularJS
. Xamarin
. SharePoint
. VBScript

Tested flavors of -
. Java, Perl, Python, NodeJS, Android, IOS(little bit)

You may also be interested in...

Comments and Discussions

GeneralThere's no need to copy the string to an array, and you shou... Pin
PIEBALDconsult8-Nov-11 17:45
memberPIEBALDconsult8-Nov-11 17:45 
Generalcool Pin
Sangunni2-Nov-11 18:24
memberSangunni2-Nov-11 18:24 
GeneralRe: Thank you Sangunni. :) Pin
RaisKazi2-Nov-11 19:04
memberRaisKazi2-Nov-11 19:04 
Generalcool Pin
Sangunni2-Nov-11 18:23
memberSangunni2-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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170518.1 | Last Updated 2 Nov 2011
Article Copyright 2011 by RaisKazi
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid