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?
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
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());
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With