繁体   English   中英

C#将字符串中的前两个分开,然后将所有其余部分保持在一起

[英]C# split first two in string, then keep all the rest together

好吧,问题可能更好。 我有一个字符串。

2008 apple micro pc computer

我希望前两个分隔符的字符串由' '拆分,然后将其余部分保持在一起。 所以它会回来

2008  
apple  
micro pc computer  

这是一个组成的字符串,所以它可以是任何东西,但它仍然是前两个分裂,然后所有其余的,不管其余的是多少

另一个例子

 apple orange this is the rest of my string and its so long  

回报

apple  
orange  
this is the rest of my string and its so long  

传递第二个参数以指定最多要分割的项目数。 在你的情况下,你传递3,所以你有前两个部分按空格分割,其余的字符串在第三个。

string myString = "2008 apple micro pc computer";
string[] parts = myString.Split(new char[] { ' ' }, 3);

这样做:

string s = "this is a test for something";            
string[] string_array =  s.Split(' ');
int length = string_array.Length;
string first = string_array[0];
string second = string_array[1];
string rest = "";
for (int i = 2; i < length; i++) rest = rest + string_array[i] + " ";
rest.TrimEnd();
  1. 在实现第2点之后,即在追加前两个单词之后,您可以对其余单词使用string.LastIIndexof
  2. 使用string.split拆分它并获取前两个
  3. 最后附加Point和Point 2的结果

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM