我对C#还不太熟悉。使用拆分时的一个问题。我以为它返回了一个字符串数组。但是一旦它到达下面的最后一行,它就崩溃了,并说我无法访问它。请勿进入。即使在拆分中,它也会找到多个'~‘。我的问题有什么解决方案吗?
String tempString = " ";
while ((tempString = streamReader.ReadLine()) != null)
{
String [] split = tempString.Split('~');
typeOfVehicle = split[0];
manufactuer = split[1];非常感谢
问题解决了。
发布于 2011-09-21 07:59:26
你假设当你拆分字符串时,你至少会有2个元素。永远不要假设。在尝试访问索引之前,请始终检查数组的长度。
发布于 2011-09-21 08:04:52
只需对异常执行catch,您很快就会发现正在读取的字符串有问题。
String[] split = tempString.Split('~');
try
{
typeOfVehicle = split[0];
manufactuer = split[1];
}
catch
{
Console.WriteLine("Oops! It didn't work.");
Console.WriteLine("The offending string was \"{0}\"", tempString);
}https://stackoverflow.com/questions/7493127
复制相似问题