Question

I build up an array of strings with

string[] parts = string.spilt(" ");

And get an array with X parts in it, I would like to get a copy of the array of strings starting at element

parts[x-2]

Other than the obvious brute force approach (make a new array and insert strings), is there a more elegant way to do this in C#?

Was it helpful?

Solution

How about 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.

OTHER TIPS

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);
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.

Use Array.Copy. It has an overload that does what you need:

Array.Copy (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.

Array.Copy Method

I guess something like:

string[] less = new string[parts.Length - (x - 2)];
Array.Copy(parts, x - 2, less, 0, less.Length);

(sans the off by 1 bug that I'm sure is in there.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top