我已經撰寫了對給定輸入進行排序的代碼,但在回傳排序后的輸入后,它將始終回傳相同的輸出。我正在 Visual Studio 中使用 .NET 5.0(當前)創建控制臺應用程式。
當我輸入“Car Apple Banana”時,它會按 words.Sorted() 排序
之后我列印出原始輸入,但它似乎也被排序了。我不知道為什么,因為我從來沒有整理過它。
當輸入為:“汽車蘋果香蕉”
我現在得到的輸出是:
蘋果香蕉車
蘋果香蕉車
雖然它需要:
蘋果香蕉車
汽車蘋果香蕉
這是主要代碼:
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
namespace _10_Words
{
class Program
{
static void Main(string[] args)
{
string[] input_1 = Console.ReadLine().Split(' ');
Words words = new Words(input_1);
Console.WriteLine(words.Sorted());
Console.WriteLine(words.Normal());
}
}
}
這是類代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _10_Words
{
class Words
{
public string[] Output { get; set; }
public Words(string[] input)
{
Output = input;
}
public string Sorted()
{
string[] sorted = Output;
Array.Sort(sorted);
string sorted_array = string.Join(" ", sorted);
return Convert.ToString(sorted_array);
}
public string Normal()
{
string[] normal = Output;
string normal_output = string.Join(" ", normal);
return Convert.ToString(normal_output);
}
}
}
uj5u.com熱心網友回復:
string[] sorted = Output;
Array.Sort(sorted);
當您呼叫 時Array.Sort,這會修改您傳遞給它的陣列。因為陣列是通過參考傳遞的,sorted并Output參考相同的陣列,它被排序。
換句話說,您Output在對元素進行排序時正在發生變化。
最簡單的解決方法是確保創建一個新陣列,其元素與舊陣列相同:
// Don't forget to include this at the top of the file
using System.Linq;
string[] sorted = Output.ToArray();
Array.Sort(sorted);
另一種解決方案是將排序更改為不改變輸入陣列并回傳一個新(已排序)陣列的方法:
// Don't forget to include this at the top of the file
using System.Linq;
string[] sorted = Output.OrderBy(x => x).ToArray();
這兩種解決方案都使用 LINQ,這使得陣列(和串列)操作更易于閱讀(恕我直言)。
uj5u.com熱心網友回復:
看來你假設這條線
string[] sorted = Output;
復制input到Output,因此您可以Output在保持input不變的情況下進行排序。
不是這種情況。
陣列是參考型別。因此,當您將類似Output陣列分配給另一個陣列變數時,例如sorted,sorted并且Output將參考相同的陣列。
如果你想要一個副本,你將不得不遍歷元素或使用輔助方法,例如Array.Copy:
sorted = new string[Output.Length];
Array.Copy(Output, sorted, Output.Length);
uj5u.com熱心網友回復:
當你寫
string[] sorted = Output;
您正在分配對陣列輸出的參考以進行排序,然后將 iy 就地排序
Array.Sort(sorted);
但由于 sorted 只是對 Output 的參考,因此您實際上是在對 Output 進行排序。更好的方法是直接列印原始陣列,然后將其排序,然后列印。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/379017.html
下一篇:餐廳選擇程式
