Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- How to delete a chosen element in array?
- 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;
- }
- }
- var strItems = new string[] { "1", "2", "3", "4", "5" };
- var list = new List<string>(strItems);
- list.Remove("3");
- strItems = list.ToArray();
- int removeIndex = Array.IndexOf(strItems, "3");
- if (removeIndex >= 0)
- {
- // continue...
- }
- 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;
- }
- public bool MyDelete(int[] array, int value) // Easy to do for strings too.
- {
- bool found = false;
- for (int i = 0; i < array.Length; ++i)
- {
- if (found)
- {
- array[i - 1] = array[i];
- }
- else if (array[i] == value)
- {
- found = true;
- }
- }
- return found;
- }
- public static T[] RemoveAt<T>(T[] array, int index) // hope there are not bugs, wrote by scratch.
- {
- int count = array.Length - 1;
- T[] result = new T[count];
- if (index > 0)
- Array.Copy(array, 0, result, 0, index - 1);
- if (index < size)
- Array.Copy(array, index + 1, result, index, size - index);
- return result;
- }
- ...
- strItems = RemoveAt(strItems, index);
Add Comment
Please, Sign In to add comment