C# - 如何交换字符串第n个值的值?

时间:2016-10-16 12:13:33

标签: c#

   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个。 我真的尝试过各种各样的东西,但我似乎无法找到一个真正有效的优雅解决方案。额外的解释会有所帮助,不,这不是我的功课。

2 个答案:

答案 0 :(得分:0)

    char newValue = char.Parse(Console.ReadLine());
    StringBuilder sb = new StringBuilder(binary);
    sb[position] = newValue;
    binary= sb.ToString();

答案 1 :(得分:0)

交换整数中的位涉及一些复杂的逻辑运算Swapping bits in a positive 32bit integer in C#,但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