[英]Issue with String.split
I am kinda new to C#. 我是C#的新手。 A problem when using split.
使用拆分时出现问题。 I thought it returned a string array.
我以为它返回了一个字符串数组。 But once it gets to the last line below it crashes and says I cant access it.
但是一旦它到达下面的最后一行就会崩溃并说我无法访问它。 Out of bounds.
出界。 Even though in the split it would have found multiple '~'.
即使在分裂中它也会发现多个'〜'。 Any solutions to my problem?
我问题的任何解决方案?
String tempString = " ";
while ((tempString = streamReader.ReadLine()) != null)
{
String [] split = tempString.Split('~');
typeOfVehicle = split[0];
manufactuer = split[1];
Thanks very much 非常感谢
Question solved. 问题解决了。
You are assuming that when you split the string you will have at least 2 elements. 您假设在拆分字符串时,您将拥有至少2个元素。 Never assume.
永远不要假设 Always check the length of the array before you attempt to access an index.
在尝试访问索引之前,请始终检查阵列的长度。
Just catch
the exception and you'll soon see that you have a problem with the string you're reading. 只是
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.