views:

251

answers:

4

I am coding VB.NET in VS2008.

I have a comma delimited string of numbers, i.e. 16,7,99,1456,1,3

I do this in VB:

Dim MyArr() As String = MyString.Split(",")

Will MyArr keep the items in the order they were in the string?

If I do this:

For Each S as String in MyString.Split(",")
    'Do something with S
    'Will my items be in the same order they were
    'in the string?
Next

I tested it and it appears to keep the sort order but will it ~always~ keep the order?

If it does not maintain the order then what is a good way to split a string and keep order?

I'm asking because MSDN Array documentation says: "The Array is not guaranteed to be sorted." So I'm a bit unsure.

+5  A: 

Yes, in your example the items will stay in the original order.

The MSDN documentation indicates that an Array is not necessarily sorted just because it's an Array, but once the items are in the Array, they won't be rearranged. The Split() operation will break it down based on the given token, preserving the order.

ahockley
Yes. I think "preserve" is the key issue to remember.
Rob Kennedy
That's the clarification I was looking for. Thanks.
rvarcher
+1  A: 

Yes, order will be maintained for these operations.

Stephen Doyle
A: 

In .NET strings are immutable objects. Long story short, the string S and those returned by Split(",") live in different memory.

Serguei
+1  A: 

Yes, String.Split walks down the string, everything will stay in order. From .NET Reflector:

private string[] InternalSplitKeepEmptyEntries(int[] sepList, int[] lengthList, int numReplaces, int count)
{
    int startIndex = 0;
    int index = 0;
    count--;
    int num3 = (numReplaces < count) ? numReplaces : count;
    string[] strArray = new string[num3 + 1];
    for (int i = 0; (i < num3) && (startIndex < this.Length); i++)
    {
        strArray[index++] = this.Substring(startIndex, sepList[i] - startIndex);
        startIndex = sepList[i] + ((lengthList == null) ? 1 : lengthList[i]);
    }
    if ((startIndex < this.Length) && (num3 >= 0))
    {
        strArray[index] = this.Substring(startIndex);
        return strArray;
    }
    if (index == num3)
    {
        strArray[index] = Empty;
    }
    return strArray;
}
Rob McCready
I misread the question a bit. Serguei has a cleaner more precise answer.
Rob McCready