我假设你用字符串的基本阵列工作:
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)
{
// 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;
}
现在strItems
将成为新的阵列,减去去除指定的值。
什么是'intAmount'和'strItems'?你正在做的for循环,这通常是一个坏主意内大量的for循环指数操纵的。 –
你能否澄清你的问题:你说[1,2,3,4,5],删除1的操作变成了[2,3,4,5,5]。你如何选择5作为要复制的元素? – ssamuel
strItems是字符串数组,intAmount是元件的数量和strInput是用户的动产删除的元素。 – user1033065