Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all.
I'm new in .Net and i want to learn.
My question is how to change characters in string. Was trying to find solution on google, but i couldn't find it.
For example: how to change string "abcd" in "badc".

I can swap first 2 characters, but i dont have idea how to change others.
This is how i done that:

C#
static string Swap(string str, int index1, int index2)
        {
            char[] c = str.ToCharArray();
            char temp = c[index1];
            c[index1] = c[index2];
            c[index2] = temp;

            return new string(c);
        }

Plz can someone help me.
Thx.
Posted

Use Loop and find odd positions and swap with one incremented even position eg: 1 with 2 and vice versa 3 by 4 and so on. use the same logic which u have written but apply the loop by calculating the length of ur string.
 
Share this answer
 
Try as below code.

C#
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]);
  }

}


Input: "AXBYCZ"
Output: "XAYBZC"

Incase length of string is odd number. Then last character will maintain its original position.

Input: "AXBYCZT"
Output: "XAYBZCT"
 
Share this answer
 
v2
I posted a tip/trick about how to do this, but this damn iPad is truncating the link. You're gonna have to search the site for it unless someone else is willing to post it (or I get home from my errands).

EDIT =======================

Extension Methods to Reverse a String and StringBuilder Object[^]
 
Share this answer
 
v2
Comments
Marcus_2 2-Sep-11 10:06am    
#realJSOP 2-Sep-11 10:34am    
Nope - I posted it when I got home.
Another option,

C#
static void Main(string[] args)
{
    string myString = "Hello world";
    Console.WriteLine(ReverseString(myString));
}

static string ReverseString(string @string)
{
    return new string(@string.Reverse().ToArray());
}


:)
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900