[英]appending to a string array in C#
string Input = "";
string[] Words = { "elephant", "lion" };
string[] Clues = { "Has trunk?", "Is gray?", "Is yellow?", "Has mane?"};
.........
Console.WriteLine("Do you want to add you own animal? y/n ? \n");
Input = Console.ReadLine();
if (Input == "Y" || Input == "y")
{
Console.WriteLine("Enter an animal name: \n");
//Array.Resize(ref Words, Words.Length + 1);
Input = Console.ReadLine();
Words[Words.Length] = Input;
Console.WriteLine("Enter 2 clues \n");
for (int i = 1; i <=2 ; i++)
{
Console.WriteLine("Clue" + i + ":");
Clues[Clues.Length] = Console.ReadLine();
}
}
这是动物游戏的标准猜测。我在Words[Words.Length] = Input;
index out of bounds
Words[Words.Length] = Input;
..输入的新动物和线索也需要在下次我玩游戏时可用。
相反, string []
使用System.Collections.Generic中的 List<T>
您可以使用Add方法添加新值,如下所示。
Console.WriteLine("Enter an animal name: \n");
Input = Console.ReadLine();
Words.Add(Input);
如果要在最后放置一个数组,则可以使用ToArray
方法。 像这样。
Words.ToArray();
将字符串添加到有限数组(例如您声明的数组)中会导致此附加项超出此数组的范围,即。 您将更多的东西挤进了无法容纳该数量的空间。 一旦创建(在编译时),此大小将固定不变,直到下一次才能更改。
我认为您正在寻找的是列表List<string>
,该List<string>
使用list.Add()
在运行时轻松动态地操作内容。
让我知道这是否回答了您的问题,或者您是否需要更多详细信息。
您可以使用List<string>
代替Array
。 您的代码引发异常,因为您试图将元素添加到超出索引的数组中。 我这样修改了您的代码;
string Input = "";
var Words = new List<string> { "elephant", "lion" };
var Clues = new List<string> { "Has trunk?", "Is gray?", "Is yellow?", "Has mane?" };
Console.WriteLine("Do you want to add you own animal? y/n ? \n");
Input = Console.ReadLine();
if (Input == "Y" || Input == "y")
{
Console.WriteLine("Enter an animal name: \n");
//Array.Resize(ref Words, Words.Length + 1);
Input = Console.ReadLine();
Words.Add(Input);
Console.WriteLine("Enter 2 clues \n");
for (int i = 1; i <= 2; i++)
{
Console.WriteLine("Clue" + i + ":");
var clueInput = Console.ReadLine();
Clues.Add(clueInput);
}
}
你为什么不使用列表而不是数组。
string Input = "";
List<string> Words = new List<string>(){ "elephant", "lion" };
List<string> Clues =new List<string>() { "Has trunk?", "Is gray?", "Is yellow?", "Has mane?"};
Console.WriteLine("Do you want to add you own animal? y/n ? \n");
Input = Console.ReadLine();
if (Input.toLower() == "y")
{
Console.WriteLine("Enter an animal name: \n");
//Array.Resize(ref Words, Words.Length + 1);
Input = Console.ReadLine();
Words.Add(Input);
Console.WriteLine("Enter 2 clues \n");
for (int i = 1; i <=2 ; i++)
{
Console.WriteLine("Clue" + i + ":");
Clues.Add(Console.ReadLine());
}
}
请遵循此。
`Console.WriteLine("Enter an animal name: \n");
//Hear Words length is 2 and Data (0 = elephant,1 = lion)
Array.Resize(ref Words, Words.Length + 1);
//Hear Words length is 3 and Data (0 = elephant,1 = lion,2 = null)
Input = Console.ReadLine();
//if you write Words[Words.Length] means you tried to access 3 index which is not available.
//You should write this.
Words[Words.Length - 1] = Input;`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.