拆分并加入C#字符串 [英] Split and join C# string
问题描述
可能重复:
首先拆分,然后加入字符串的子集
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.
示例:
theString = "Some Very Large String Here"
将成为:
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.
因此它将变为:
firstElem = "Some";
restOfArray = "Very Large String Here"
我知道我可以将theArray[0]
用作第一个元素,但是如何将数组的其余部分隐藏为一个新字符串呢?
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?
推荐答案
您可以使用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);
这使您不必加入:
string restOfArray = array[1];
这篇关于拆分并加入C#字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!