Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does String.Split method ensure order in result array?

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?

like image 218
iburlakov Avatar asked Dec 29 '11 06:12

iburlakov


People also ask

Does string split preserve order?

Yes, . split() always preserves the order of the characters in the string.

Does string split return an array?

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.

What does the string split method do?

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.

Does split maintain order Java?

split(String regex) method is guaranteed to maintain the original order of the message.


1 Answers

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.

like image 78
Uwe Keim Avatar answered Oct 10 '22 02:10

Uwe Keim