拆分并加入 C # 字符串

可能的复制品:
首先拆分,然后加入字符串 的子集

我试图将一个字符串拆分成一个数组,取出第一个元素(使用它) ,然后将数组的其余部分合并成一个单独的字符串。

例如:

theString = "Some Very Large String Here"

会变成:

theArray = [ "Some", "Very", "Large", "String", "Here" ]

然后我想设置变量中的第一个元素,并在以后使用它。

然后我想将数组的其余部分连接到一个新字符串中。

所以它会变成:

firstElem = "Some";
restOfArray = "Very Large String Here"

我知道可以对第一个元素使用 theArray[0],但是如何将数组的其余部分连接到一个新字符串呢?

202445 次浏览

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];

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.