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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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

Method 3

You could use String.Split, it has an overloaded method which accepts max no of splits.

var input = "10,12-JUL-16,11,0"; // input string.

input.Split(new char[]{','},3)[1]

Check the Demo

Method 4

Yes, you can:

string[] parts = str.Split(',');

Then your second part is in parts[1].

or:

string secondPart = str.Split(',')[1];

or with Linq:

string secondPart = str.Split(',').Skip(1).FirstOrDefault();
if (secondPart != null)
{
    ...
}
else
{
    ... 
}

Also you can use not only one symbol for string splitting, i.e.:

string secondPart = str.Split(new[] {',', '.', ';'})[1];

Method 5

Here’s a way though the rest have already mentioned it.

string input = "10,12-JUL-16,11,0";
string[] parts = input.Split(',');
Console.WriteLine(parts[1]);

Output:

12-JUL-16

Demo


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x