Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string and get Second value only

I wonder if it's possible to use split to divide a string with several parts that are separated with a comma, like this:

10,12-JUL-16,11,0

I just want the Second part, the 12-JUL-16 of string and not the rest?

like image 736
Gaurav_0093 Avatar asked Jul 20 '16 09:07

Gaurav_0093


2 Answers

Yes:

var result = str.Split(',')[1];

OR:

var result = str.Split(',').Skip(1).FirstOrDefault();

OR (Better performance - takes only first three portions of the split):

var result = str.Split(new []{ ',' }, 3).Skip(1).FirstOrDefault();
like image 131
Zein Makki Avatar answered Oct 21 '22 05:10

Zein Makki


Use LINQ's Skip() and First() or FirstOrDefault() if you are not sure there is a second item:

string s = "10,12-JUL-16,11,0";
string second = s.Split(',').Skip(1).First();

Or if you are absolutely sure there is a second item, you could use the array accessor:

string second = s.Split(',')[1];
like image 30
Patrick Hofman Avatar answered Oct 21 '22 04:10

Patrick Hofman