Click here to Skip to main content
12,349,911 members (24,629 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

19.2K views
1 bookmarked
Posted

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.

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)

Share

About the Author

RaisKazi
Technical Lead
United States United States
No Biography provided

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.

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