我建立了一个字符串数组
string[] parts = string.spilt(" ");
并获得一个包含 X 部分的数组,我想获得从元素开始的字符串数组的副本
parts[x-2]
除了明显的蛮力方法(创建一个新数组并插入字符串)之外,在 C# 中是否有更优雅的方法来做到这一点?
I remembered answering this question and just learned about a new object that may provide a high performance method of doing what you want.
Take a look at ArraySegment<T>
. It will let you do something like.
string[] parts = myString.spilt(" ");
int idx = parts.Length - 2;
var stringView = new ArraySegment<string>(parts, idx, parts.Length - idx);
Array.Copy 怎么样?
http://msdn.microsoft.com/en-us/library/aa310864(VS.71).aspx
Array.Copy Method (Array, Int32, Array, Int32, Int32)
Copies a range of elements from an Array starting at the specified source index and pastes them to another Array starting at the specified destination index. The length and the indexes are specified as 32-bit integers.
List<string> parts = new List<string>(s.Split(" "));
parts.RemoveRange(0, x - 2);
Assuming that List<string>(string[])
is optimized to use the existing array as a backing store instead of doing a copy operation this could be faster than doing an array copy.
使用Array.Copy。它有一个重载,可以满足您的需要:
Array.Copy (Array, Int32, Array, Int32, Int32)
从指定源索引开始的数组中复制一系列元素,并将它们粘贴到从指定目标索引开始的另一个数组。
我猜是这样的:
string[] less = new string[parts.Length - (x - 2)];
Array.Copy(parts, x - 2, less, 0, less.Length);
(我确信其中存在 1 个错误。)