简体   繁体   English

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

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

Okay, the question could probably a phrased better. 好吧,问题可能更好。 I have a string. 我有一个字符串。

2008 apple micro pc computer

i want the string split by ' ' for the first 2 delimiters and then keep the rest together. 我希望前两个分隔符的字符串由' '拆分,然后将其余部分保持在一起。 so it'll return 所以它会回来

2008  
apple  
micro pc computer  

This is a made up string so it could be anything, but it's still first 2 split, then all the rest no matter how much is all the rest 这是一个组成的字符串,所以它可以是任何东西,但它仍然是前两个分裂,然后所有其余的,不管其余的是多少

Another example 另一个例子

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

returns 回报

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

Pass a second argument to specify how many items at max to split into. 传递第二个参数以指定最多要分割的项目数。 In your case, you'd pass 3 so you have the first two parts split by space, and the rest of the string in the third. 在你的情况下,你传递3,所以你有前两个部分按空格分割,其余的字符串在第三个。

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

This would do it: 这样做:

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. You can use string.LastIIndexof for the rest of the words after implementing point 2 ie after append the first two words. 在实现第2点之后,即在追加前两个单词之后,您可以对其余单词使用string.LastIIndexof
  2. Split it using string.split and fetch first two 使用string.split拆分它并获取前两个
  3. Finally append the result of Point and Point 2 最后附加Point和Point 2的结果

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

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