正在删除数组元素(C#)

本文关键字:数组元素 删除 | 更新日期: 2023-09-27 18:21:49

我正在尝试删除用户输入索引和值处的int数组元素(意味着用下一个替换数组元素),但在输出中,它给了我两次元素。示例输入数组是:1 2 3 4 5 6,用户说删除3索引处的第三个元素,则输出是:1 1 2 4 4 5 6什么是解决方案plz。不使用任何函数或库。

Console.WriteLine("Enter The Length Of Linear Array");
int length = Convert.ToInt32(Console.ReadLine());
int[] LinearArr = new int[length + 2];
Console.WriteLine("Maximum Number Of Inputs : {0}", length);

for (int i = 1; i < LinearArr.Length - 1; i++)
{
    LinearArr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("What Number You Want To Delete And At What Index");
int InsertNum2 = Convert.ToInt32(Console.ReadLine());
int k2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number :{0} And Index :{1}",InsertNum2,k2);
InsertNum2 = LinearArr[k2];
for (int i = k2; i < LinearArr.Length-1; i++)
{
    LinearArr[k2] = LinearArr[k2 + 1];

}
length = length - 1;
for (int i = 1; i < LinearArr.Length-1; i++)
{
    Console.WriteLine(LinearArr[i]);
}
//Input  :1 2 3 4 5 6
//output :1 2 4 4 5 6

正在删除数组元素(C#)

您的代码的问题是您在:LinearArr[k2] = LinearArr[k2 + 1];中使用k2,而应该使用i。我认为你的方法不是一个好方法,也许下面的方法会符合你的要求:

Console.WriteLine("Enter The Length Of Linear Array");
int length = Convert.ToInt32(Console.ReadLine());
int[] LinearArr = new int[length + 2];
Console.WriteLine("Maximum Number Of Inputs : {0}", length);

for (int i = 1; i < LinearArr.Length - 1; i++)
{
    LinearArr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("What Number You Want To Delete And At What Index");
int InsertNum2 = Convert.ToInt32(Console.ReadLine());
int k2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Number :{0} And Index :{1}",InsertNum2,k2);
//create a new array with length = LinearArray - 1
int[] newArray = new int[LinearArray.Length - 1];
int currentIndex = 0;
InsertNum2 = LinearArr[k2];
for (int i = 0; i < LinearArr.Length; i++)
{
    //if i == index want to delete, ignore
    if(i != k2) 
    {
        newArray[currentIndex] = LinearArray[i];
        currentIndex++;
    }
}
length = length - 1;
for (int i = 0; i < newArray.Length-1; i++)
{
    Console.WriteLine(newArray[i]);
}

您不能在运行时从数组的中间移除项。您的最佳选择是将数组转换为列表。

        var a = new[] { "A", "B", "C" }.ToList();
        a.RemoveAt(1);
        foreach (var x in a)
            Console.WriteLine(x);

如果由于某种原因不能使用列表代替数组,则可以逐个移动元素,最后调整数组的大小。

        var a = new[] { "A", "B", "C", "D", "E", "F" };
        for (var i = 1; i < a.Length - 1; i++)
            a[i] = a[i + 1];
        Array.Resize(ref a, a.Length - 1);
        foreach (var x in a)
            Console.WriteLine(x);

将数组转换为列表,移除元素并将列表转换回数组。

var numList = LinearArr.ToList();
numList.Remove(k2);
LinearArr = numList.ToArray();

您应该使用索引i而不是k2

for (int i = k2; i < LinearArr.Length - 1; i++)
    LinearArr[i] = LinearArr[i + 1];
}

k2不变)