Guest User

Untitled

a guest
Aug 15th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. How to delete a chosen element in array?
  2. strInput = Console.ReadLine();
  3. for (int i = 0; i < intAmount; i++)
  4. {
  5. if (strItems[i] == strInput)
  6. {
  7.  
  8.  
  9. strItems[i] = null;
  10. for (int x = 0; x < intAmount-i; x++)
  11. {
  12. i = i + 1;
  13. strItems[i - 1] = strItems[i];
  14. }
  15.  
  16. intAmount = intAmount - 1;
  17. }
  18. }
  19.  
  20. var strItems = new string[] { "1", "2", "3", "4", "5" };
  21.  
  22. var list = new List<string>(strItems);
  23. list.Remove("3");
  24. strItems = list.ToArray();
  25.  
  26. int removeIndex = Array.IndexOf(strItems, "3");
  27.  
  28. if (removeIndex >= 0)
  29. {
  30. // continue...
  31. }
  32.  
  33. string strInput = Console.ReadLine();
  34. string[] strItems = new string[] { "1", "2", "3", "4", "5" };
  35.  
  36. int removeIndex = Array.IndexOf(strItems, strInput);
  37.  
  38. if (removeIndex >= 0)
  39. {
  40. // declare and define a new array one element shorter than the old array
  41. string[] newStrItems = new string[strItems.Length - 1];
  42.  
  43. // loop from 0 to the length of the new array, with i being the position
  44. // in the new array, and j being the position in the old array
  45. for (int i = 0, j = 0; i < newStrItems.Length; i++, j++)
  46. {
  47. // if the index equals the one we want to remove, bump
  48. // j up by one to "skip" the value in the original array
  49. if (i == removeIndex)
  50. {
  51. j++;
  52. }
  53.  
  54. // assign the good element from the original array to the
  55. // new array at the appropriate position
  56. newStrItems[i] = strItems[j];
  57. }
  58.  
  59. // overwrite the old array with the new one
  60. strItems = newStrItems;
  61. }
  62.  
  63. public bool MyDelete(int[] array, int value) // Easy to do for strings too.
  64. {
  65. bool found = false;
  66. for (int i = 0; i < array.Length; ++i)
  67. {
  68. if (found)
  69. {
  70. array[i - 1] = array[i];
  71. }
  72. else if (array[i] == value)
  73. {
  74. found = true;
  75. }
  76. }
  77. return found;
  78. }
  79.  
  80. public static T[] RemoveAt<T>(T[] array, int index) // hope there are not bugs, wrote by scratch.
  81. {
  82. int count = array.Length - 1;
  83. T[] result = new T[count];
  84.  
  85. if (index > 0)
  86. Array.Copy(array, 0, result, 0, index - 1);
  87. if (index < size)
  88. Array.Copy(array, index + 1, result, index, size - index);
  89.  
  90. return result;
  91. }
  92.  
  93. ...
  94. strItems = RemoveAt(strItems, index);
Add Comment
Please, Sign In to add comment