Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a chosen element in array?

Tags:

arrays

c#

I have this assignment where I must delete a chosen element from an array, so I came up with this code:

strInput = Console.ReadLine();
for (int i = 0; i < intAmount; i++)
{
    if (strItems[i] == strInput)
    {
        strItems[i] = null;
        for (int x = 0; x < intAmount-i; x++)
        {
            i = i + 1;
            strItems[i - 1] = strItems[i];
        }
        intAmount = intAmount - 1;
    }
}

The problem is that, suppose I have an array [1,2,3,4,5,], and I want to delete 1. The output would be [2,3,4,5,5]. This also happens when I choose 2, but it does not happen when I choose any other number.

What am I doing wrong?

like image 905
user1033065 Avatar asked Nov 07 '11 03:11

user1033065


People also ask

How do I remove a specific element from an array?

pop() function: This method is use to remove elements from the end of an array. shift() function: This method is use to remove elements from the start of an array. splice() function: This method is use to remove elements from the specific index of an array.

Can we delete an element from an array?

Java arrays do not provide a direct remove method to remove an element. In fact, we have already discussed that arrays in Java are static so the size of the arrays cannot change once they are instantiated. Thus we cannot delete an element and reduce the array size.

How do I remove a specific data from a list?

To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.


2 Answers

I'm assuming you are working with a basic array of strings:

var strItems = new string[] { "1", "2", "3", "4", "5" };

In .NET, that array is always going to be 5 elements long. In order to remove an element, you are going to have to copy the remaining elements to a new array and return it. Setting the value at a position to null does not remove it from the array.

Now, with things like LINQ this is very easy (not shown here), or you could cheat using the List<> collection and do this:

var list = new List<string>(strItems);
list.Remove("3");
strItems = list.ToArray();

But I don't think that's going to teach you anything.

The first step is to find the index of the element you wish to remove. You can use Array.IndexOf to help you out. Let's find the middle element, "3":

int removeIndex = Array.IndexOf(strItems, "3");

If the element was not found, it will return a -1, so check for that before doing anything.

if (removeIndex >= 0)
{
     // continue...
}

Finally you have to copy the elements (except the one at the index we don't want) to a new array. So, altogether, you end up with something like this (commented for explanation):

string strInput = Console.ReadLine();
string[] strItems = new string[] { "1", "2", "3", "4", "5" };

int removeIndex = Array.IndexOf(strItems, strInput);

if (removeIndex >= 0)
{
    // declare and define a new array one element shorter than the old array
    string[] newStrItems = new string[strItems.Length - 1];

    // loop from 0 to the length of the new array, with i being the position
    // in the new array, and j being the position in the old array
    for (int i = 0, j = 0; i < newStrItems.Length; i++, j++)
    {
        // if the index equals the one we want to remove, bump
        // j up by one to "skip" the value in the original array
        if (i == removeIndex)
        {
            j++;
        }

        // assign the good element from the original array to the
        // new array at the appropriate position
        newStrItems[i] = strItems[j];
    }

    // overwrite the old array with the new one
    strItems = newStrItems;
}

And now strItems will be the new array, minus the value specified for removal.

like image 170
Cᴏʀʏ Avatar answered Sep 22 '22 00:09

Cᴏʀʏ


Arrays in C# are of a fixed size - once initialized you can only modify items, but you cannot add or remove items. If you want to delete an item from a collection you have two options:

1.) Create a new array that has all members of the original array minus the one you want to remove.

2.) Use a collection type that is resizable and allows to add or remove items like List<T> (List<int> in your case). This is what you would do in the "real world" if your collection is not static.

like image 27
BrokenGlass Avatar answered Sep 21 '22 00:09

BrokenGlass