I am kinda new to 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. 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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.