拆分并连接 C# 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12961868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split and join C# string
提问by Gaui
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?
我知道我可以theArray[0]用于第一个元素,但是如何将数组的其余部分连接到一个新字符串?
采纳答案by Reed Copsey
You can use string.Splitand string.Join:
您可以使用string.Split和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];
回答by Sheridan Bulger
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.
您可以拆分和连接字符串,但为什么不使用子字符串?然后你只得到一个分割,而不是将字符串分割成 5 个部分并重新连接它。最终结果是相同的,但子字符串可能要快一点。
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);
}
回答by Sheridan Bulger
Well, here is my "answer". It uses the fact that String.Splitcan be told hold many items it should split to (which I found lacking in the other answers):
好吧,这是我的“答案”。它使用了一个事实,即String.Split可以被告知包含许多它应该拆分的项目(我发现其他答案中缺少这些项目):
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 Substringmethod, just by a different means.
这与Substring方法非常相似,只是方式不同。

