在进行流畅的谷歌搜索后,我们没有得到答案,所以问题是:
String.Split
方法是否确保返回的子字符串与它们在初始字符串中的位置相对应?
string.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对于string.Split
的文档也列出了结果与原始字符串中顺序相同的示例。
正如Jim Mischel上面指出的那样,这只是当前的实现,可能会改变。
split
方法的结果是一致有序的。如果我不能依赖顺序,那么String.Split
几乎就没有用处了。我认为这个行为没有被明确说明,是因为没有人想到要指出这么“显而易见”的事情。我认为他们应该记录这种行为。 - Jim MischelString
但保存了对另一个String
的引用以及起始偏移量和长度(如果GC特殊处理,则可以提高性能),那么这可能是有意义的... - supercat