我假设您正在使用基本的字符串数组:
var strItems = new string[] { "1", "2", "3", "4", "5" };
在.NET中,该数组始终将有5个元素的长度。为了删除一个元素,您需要将其余的元素复制到新数组中并返回它。将位置上的值设置为null
并不能从数组中删除它。
现在,使用LINQ之类的东西非常容易(此处未展示),或者您可以使用List<>
集合来欺骗操作,像这样:
var list = new List<string>(strItems);
list.Remove("3");
strItems = list.ToArray();
但我认为这并不能让你学到什么。
第一步是找到要删除的元素的索引。您可以使用 Array.IndexOf
来帮助您完成。我们来找到中间的元素 "3":
int removeIndex = Array.IndexOf(strItems, "3");
如果未找到该元素,它将返回-1,在执行任何操作之前,请检查是否存在。
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)
{
string[] newStrItems = new string[strItems.Length - 1];
for (int i = 0, j = 0; i < newStrItems.Length; i++, j++)
{
if (i == removeIndex)
{
j++;
}
newStrItems[i] = strItems[j];
}
strItems = newStrItems;
}
现在strItems
将是新的数组,减去指定要移除的值。
intAmount
和strItems
是什么?你在for循环中进行了许多索引操作,这通常是一个不好的想法。 - Cᴏʀʏ