jason jason - 3 months ago 22
C# Question

Manual string split in C#

In my code, I am attempting to manipulate a string:

Some text - 04.09.1996 - 40-18


I'd like to split this into three substrings:
Some text
,
04.09.1996
, and
40-18
.

When I use the
Split
method with a hyphen as a separator, the return value is an array of four strings:
Some text
,
04.09.1996
,
40
, and
18
. How can I make this code work as described above?

Thanks.

Answer

You should just split with spaces around -:

 .Split(new[] {" - "}, StringSplitOptions.RemoveEmptyEntries);

See C# demo

var res = "Some text - 04.09.1996 - 40-18".Split(new[] {" - "}, StringSplitOptions.RemoveEmptyEntries);
foreach (var s in res)
    Console.WriteLine(s);

Result:

Some text
04.09.1996
40-18