Splitting a string with another string should be a simple matter in C#. However it is not as intuitive as you might think. I would have thought that a simple .split() method would have to be called with a string as parameter (the string to split on), but that was not the case. Below is a way to do it:
var text = "first half SpltOnThis second half";
var splittedString = text.Split(new[] { "SpltOnThis" }, StringSplitOptions.None);
//splittedString will contain: "first half " and " second half".
In the above we use an overload of the Split method, which takes an array of strings to split on, however in the above we only give it one string.
And here is an example where I have wrapped it in a nice extension method, so you do not have to copy/paste the above again and again:
public static string[] Split(this string str, string delimeter)
{
return str.Split(new[] { delimeter }, StringSplitOptions.None);
}
You can find a full working example with a unit test below:
public class UnitTests
{
[Fact]
public void TestSplitOnCharacters()
{
var abc = "abcdefghi";
var splitOnDef = abc.Split("def");
Assert.Equal("abc", splitOnDef[0]);
Assert.Equal("ghi", splitOnDef[1]);
}
}
public static class Extentions
{
public static string[] Split(this string str, string delimeter)
{
return str.Split(new[] { delimeter }, StringSplitOptions.None);
}
}
That is it
That is it, please leave a comment down below if you found this helpful :)