Does String.Split method ensure order in result array?
According to what ILSpy shows on the internals of string.Split
, the answer is yes.
private string[] InternalSplitKeepEmptyEntries(
int[] sepList, int[] lengthList, int numReplaces, int count)
{
int num = 0;
int num2 = 0;
count--;
int num3 = (numReplaces < count) ? numReplaces : count;
string[] array = new string[num3 + 1];
int num4 = 0;
while (num4 < num3 && num < this.Length)
{
array[num2++] = this.Substring(num, sepList[num4] - num);
num = sepList[num4] + ((lengthList == null) ? 1 : lengthList[num4]);
num4++;
}
if (num < this.Length && num3 >= 0)
{
array[num2] = this.Substring(num);
}
else
{
if (num2 == num3)
{
array[num2] = string.Empty;
}
}
return array;
}
All elements (e.g. the array
variable) are always processed in ascending order and no sorting occurs.
The MSDN documentation for string.Split
also lists examples which have results in the same order as their order in the original string.
As Jim Mischel points out above, this is only the current implementation, which might change.
Yes is does. Otherwise it would be rather useless.