2011-12-29 47 views
5

流利的谷歌搜索並沒有給出答案,所以問題是:String.Split方法確保結果數組中的順序嗎?

String.Split方法並確保根據他們在初始字符串位置導致子的順序?

謝謝。

+0

現在我認爲它會是的 – V4Vendetta

+2

你有一個很好的答案,並且可能是我們所能期待的最好的答案。不過,我必須指出,只是因爲當前的實施將事情按照預期的順序進行,這不是一個真正的保證。也就是說,BCL團隊改變訂單是愚蠢的。它只是沒有任何意義。 –

+0

感謝您的有用評論吉姆。無論如何改變String.Split中的順序是不太可能的,可能最好避免從split方法中獲得一致的順序。 – iburlakov

回答

8

根據ILSpystring.Split的內部顯示的內容,回答是

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; 
} 

所有元件(例如,array變量)按升序排列經常被加工和不排序發生。

MSDN documentation for string.Split也列出了一些例子,其結果與原始字符串中的順序相同。

由於Jim Mischel指出上面,這只是目前的實施,這可能會改變。

+4

堅實的證明。還有不錯的速度。 – captncraig

1

是的。否則,這將是無用的。