Split string and get Second value only

前端 未结 5 736
闹比i
闹比i 2021-01-01 02:05

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

相关标签:
5条回答
  • 2021-01-01 02:07

    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];
    
    0 讨论(0)
  • 2021-01-01 02:17

    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

    0 讨论(0)
  • 2021-01-01 02:28

    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

    0 讨论(0)
  • 2021-01-01 02:29

    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];
    
    0 讨论(0)
  • 2021-01-01 02:30

    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();
    
    0 讨论(0)
提交回复
热议问题