By default the Split
method includes empty strings in the array. So you're cEdge
array is has a size of 17 with around 8 of the elements being empty strings. So when you try iterating through the array, the length of the empty string is 0 and you try to subtract 1 which places you out of bounds on the array.
You've got a couple of options here. You can place an if statement to ensure the length of cEdge
is 3 characters or update the Split method to use one of the overloads that will automatically remove these empty elements.
Here's how you would use the overload:
string[] edges = testStr.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Edit
Just realized I didn't really explain why you get the extra empty groups. The empty elements appear because you supplied the split function with an array of delimiters. The function then uses the array to match on ANY one of the delimiters and breaks it into unique elements. There's a perfect example in you're situation where this makes a difference. If your source string testStr
was to contain a space in one of the fields it will actually break that field in half because you supplied a space into the delimiter list.
As the MSDN article puts it:
Each element of separator defines a separate delimiter character. If two delimiters are adjacent, or a delimiter is found at the beginning or end of this instance, the corresponding array element contains Empty.
So for instance:
string testStr = "AB5, BC4, CD8 Test, DC8";
string [] edges = testStr.Split(", ".ToCharArray());
In this case most people assume that we would end up with an array that looks something like this:
+----------------------------+
| AB5 | BC4 | CD8 Test | DC8 |
+----------------------------+
However the actual output of this method would be more like this:
+------------------------------+
| AB5 | BC4 | CD8 | Test | DC8 |
+------------------------------+
To get the desired output every time, a more robust solution would look something like this:
String[] edges = Regex.Split(testStr, Regex.Escape(", "), RegexOptions.None);
If the split happens to be within a tight loop you may want to consider compiling the regex before entering the loop, but that's a different problem.