简体   繁体   中英

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.

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. Split it using string.split and fetch first two
  3. Finally append the result of Point and Point 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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