Fluent googling doesn't give an answer, so question is:
Does String.Split
method ensure order of resulted substrings in according to they position in initial string?
Yes, . split() always preserves the order of the characters in the string.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string.
The Split method extracts the substrings in this string that are delimited by one or more of the strings in the separator parameter, and returns those substrings as elements of an array. The Split method looks for delimiters by performing comparisons using case-sensitive ordinal sort rules.
split(String regex) method is guaranteed to maintain the original order of the message.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With