6

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#?

asked Aug 27, 2008 at 19:39

5 Answers 5

5

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);
answered Dec 18, 2008 at 23:38

Comments

2

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.

answered Aug 27, 2008 at 19:43

Comments

0
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.

answered Dec 10, 2008 at 0:24

Comments

-1

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.

answered Aug 27, 2008 at 19:42

Comments

-1

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

answered Aug 27, 2008 at 19:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.