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";
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. :)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.