Split string and get Second value only

2020-02-26 12:56发布

问题:

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?

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


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


回答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



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


回答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