簡體   English   中英

C#-如何交換字符串的第n個值?

[英]C# - How to swap the value of the nth value of a string?

   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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM