本文介绍了反转两位数后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在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?
推荐答案
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();
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
这篇关于反转两位数后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!