Possible Duplicate:
First split then join a subset of a string
I'm trying to split a string into an array, take first element out (use it) and then join the rest of the array into a seperate string.
Example:
theString = "Some Very Large String Here"
Would become:
theArray = [ "Some", "Very", "Large", "String", "Here" ]
Then I want to set the first element in a variable and use it later on.
Then I want to join the rest of the array into a new string.
So it would become:
firstElem = "Some";
restOfArray = "Very Large String Here"
I know I can use theArray[0]
for the first element, but how would I concatinate the rest of the array to a new string?
You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.
string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');
if (lnSpace > -1)
{
string lcFirst = lcStart.Substring(0, lnSpace);
string lcRest = lcStart.Substring(lnSpace + 1);
}
Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];
This is very similar to the Substring
method, just by a different means.
Source: Stackoverflow.com