Click here to Skip to main content
14,266,079 members
Rate this:
Please Sign up or sign in to vote.
See more:
i am using this code in c#
char[] arr = textBox1.Text.ToCharArray();
   Array.Reverse(arr);
   textBox2.Text=new string(arr);

it will reverse tha whole string abcd as dcba but i want to reverse it like badc but this code is not working for this case...
can anyone help me?
Posted
Updated 18-Mar-12 5:24am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

If you are wanting to limit the reverse function, you are going to have to write the function yourself.
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Revewrse will always just rverese the complete arry - string, int, it doesn't matter:
1 2 3 4 5
becomes
5 4 3 2 1
If you want a "special swap then you have to implement it yourself - which is not so simple...

string input = "AbCdEfGh";
StringBuilder sb = new StringBuilder(input.Length);
for (int i = 0; i < input.Length / 2; i++)
    {
    int index = i * 2;
    sb.Append(input[index + 1]);
    sb.Append(input[index]);
    }
if (input.Length % 2 == 1)
    {
    sb.Append(input[input.Length - 1]);
    }
string output = sb.ToString();
   
Comments
ProEnggSoft 18-Mar-12 12:37pm
   
5!
Monjurul Habib 1-Apr-12 14:45pm
   
5!
Rate this:
Please Sign up or sign in to vote.

Solution 4

The solution 2 is very good.
An alternate method is
string s = "AbCdEfG";
char[] chars = s.ToCharArray();
//Create keys array from the indices of characters 0 1 2 3 4 5 6 =>  2 1 4 3 6 5 8
int[] keys = Array.ConvertAll(chars, x => {int ind = s.IndexOf(x); return ind % 2 == 0 ? ind+2 : ind;});
//Use the Sort method of Array class to sort chars array using keys array
Array.Sort(keys,chars);
string alternateReversedString = new string(chars);

//Or 

string s = "AbCdEfG";
char[] chars = s.ToCharArray();
//swap adjacent characters
char temp;
for(int i = 1; i < chars.Length; i += 2){
   temp=chars[i];
   chars[i]=chars[i-1];
   chars[i-1]=temp;
}
string alternateReversedString = new string(chars);

//The alternateReversedString will be
//bAdCfEG
   
v2
Comments
Monjurul Habib 1-Apr-12 14:45pm
   
5!
ProEnggSoft 1-Apr-12 21:35pm
   
Thank you very much. It seems your vote is not updated in the server.
Monjurul Habib 2-Apr-12 3:42am
   
:) hope it will now..
ProEnggSoft 2-Apr-12 3:49am
   
Yes it is. Thank you.

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100