删除数组元素(C#)

时间:2014-09-13 16:55:03

标签: c#

我试图在用户输入索引和值处删除一个int数组元素(意味着用下一个替换数组元素)所以它正在做但在输出中它给了我两次示例输入数组:1 2 3 4 5 6并且用户说删除3索引处的第3个元素然后输出是: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

4 个答案:

答案 0 :(得分:1)

您无法在运行时从数组中间删除项目。您最好的选择是将数组转换为列表。

        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);

答案 1 :(得分:1)

您的代码问题是您在k2中使用LinearArr[k2] = LinearArr[k2 + 1];,您应该使用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]);
}

答案 2 :(得分:0)

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

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

答案 3 :(得分:0)

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

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

k2不会改变)