Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
jason Avatar asked Aug 16 '16 11:08

jason


3 Answers

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
like image 168
Wiktor Stribiżew Avatar answered Sep 29 '22 00:09

Wiktor Stribiżew


Use this overload of string split to only get 3 parts:

var s = "Some text - 04.09.1996 - 40-18";
var parts = s.Split(new[] { '-' }, 3);

I'm assuming you also want to trim the spaces too:

var parts = s.Split(new[] { '-' }, 3)
    .Select(p => p.Trim());
like image 34
DavidG Avatar answered Sep 29 '22 00:09

DavidG


I would be wary of "-" or " - " appearing in "Some text", as I assume that you are interested in that as a place holder. If you are certain that "Some text" will not contain "-" than the other answers here are good, simple and readable. Otherwise we need to rely on something that we know is constant about the string. It looks to me like the thing that is constant is the last 3 hyphens. So I would try split on "-" and put the last pair back together like

string input = "Some text - 04.09.1996 - 40-18";
string[] foo = input.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
int length = foo.Length;
string[] bar = new string[3];

//put "some text" back together
for(int i=0; i< length - 3;i++)
{
   bar[0] += foo[i];
}

bar[1] = foo[length - 3];
bar[2] = foo[length - 2] + "-" + foo[length - 1];
like image 42
neverlucky13 Avatar answered Sep 29 '22 00:09

neverlucky13