反转两位数后 [英] reverse after evert two digits

查看:77
本文介绍了反转两位数后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在c#中使用此代码

i am using this code in c#

char[] arr = textBox1.Text.ToCharArray();
   Array.Reverse(arr);
   textBox2.Text=new string(arr);


它会将整个字符串abcd反转为dcba,但我想像badc一样反转它,但是此代码不适用于这种情况...
有人可以帮我吗?


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?

推荐答案

如果您想限制反向功能,则必须自己编写该功能.
If you are wanting to limit the reverse function, you are going to have to write the function yourself.


Revewrse将始终仅显示整个arry-string,int,没关系:
Revewrse will always just rverese the complete arry - string, int, it doesn''t matter:
1 2 3 4 5

成为

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();


解决方案2很好.
另一种方法是
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


这篇关于反转两位数后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆