user222427
user222427

Reputation:

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  

Upvotes: 4

Views: 3803

Answers (3)

coldandtired
coldandtired

Reputation: 1043

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();

Upvotes: 0

Pankaj
Pankaj

Reputation: 10095

  1. You can use string.LastIIndexof for the rest of the words after implementing point 2 i.e 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

Upvotes: -1

BoltClock
BoltClock

Reputation: 723498

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);

Upvotes: 23

Related Questions