c# -如何交换字符串的第n个值
本文关键字:字符串 个值 交换 何交换 | 更新日期: 2023-09-27 18:13:19
Console.WriteLine("Please enter a decimal number:");
int decNumber = int.Parse(Console.ReadLine());
string binary = Convert.ToString((long)decNumber, 2);
Console.WriteLine("'n" + "The binary conversion of the number {0} is: {1}", decNumber, binary);
Console.WriteLine("'n" + "Please select a bit position: ");
int position = int.Parse(Console.ReadLine());
Console.WriteLine("'n" + "Please select a new value to replace the old one: ");
int newValue = int.Parse(Console.ReadLine());
你好,
基本上,我想要这个程序做的是将十进制数转换为二进制数,然后替换二进制表示的第n个位置值。我真的尝试了各种各样的方法,但我似乎就是找不到一个真正有效的优雅解决方案。额外的解释会有帮助,不,这不是我的家庭作业。
char newValue = char.Parse(Console.ReadLine());
StringBuilder sb = new StringBuilder(binary);
sb[position] = newValue;
binary= sb.ToString();
在c#中交换32位正整数的位涉及一些复杂的逻辑运算,但BitArray
可以使位更容易:
static int swapBits(int i, int position1, int position2)
{
// convert int i to BitArray
int[] intArray = { i };
var bitArray = new System.Collections.BitArray(intArray);
// swap bits
var bit1 = bitArray[position1];
bitArray[position1] = bitArray[position2];
bitArray[position2] = bit1;
// convert bitArray to int i
bitArray.CopyTo(intArray, 0);
i = intArray[0];
return i;
}
请注意,位置从0开始,从右边开始,因此,例如
int i = swapBits(3, 0, 2); // 3 becomes 6