Split and join C# string

C#ArraysString

C# Problem Overview


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

C# Solutions


Solution 1 - C#

You can use string.Split and string.Join:

string theString = "Some Very Large String Here";
var array = theString.Split(' ');
string firstElem = array.First();
string restOfArray = string.Join(" ", array.Skip(1));

If you know you always only want to split off the first element, you can use:

var array = theString.Split(' ', 2);

This makes it so you don't have to join:

string restOfArray = array[1];

Solution 2 - C#

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.

Solution 3 - C#

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

		

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGauiView Question on Stackoverflow
Solution 1 - C#Reed CopseyView Answer on Stackoverflow
Solution 2 - C#user166390View Answer on Stackoverflow
Solution 3 - C#Sheridan BulgerView Answer on Stackoverflow