The string.Split() in .NET can be cumbersome to use. With many overloads you must specify an array even when passing a single delimiter (in fact only one overload is marked with params).
Is there any such alternative? Is there a way of accomplishing the task without creating arrays.
The issue is that there are two conflicting best practices in developing such an API(they are both good practices and usually do not conflict except in this particular case):
params
parameter can/must appear as the last parameter.So you have the first overload:
Split(params char[] separator)
Which leverages the params
keyword so that you don't explicitly need to create an array as that is done implicitly.
The other overloads follow the second guideline, maintaining the separator
parameter as the first parameter, but therefore cannot specify the params
keyword since that can only appear on the last parameter.
So it's a design choice balanced between the two best practices. In this case, they followed the maintain-parameter-order guideline, and did not use the params
keyword on the other overloads because it is not allowed when it is followed by others parameters.
You could implement your own static methods or extensions where the separator
parameter is always the last parameter, and therefore can always specify params
with it. Basically you could make the decision to favor the first guideline and disregard the second:
public string[] Split(int count, StringSplitOptions options, params char[] separator)
You have to be careful when versioning class libraries and evolving APIs. There are scenarios where introduction of a new params
overload will allow it to match old overloads ambiguously and break the code of projects consuming it.
If you want to avoid writing overload extensions, as Craig W. points out "x".ToCharArray()
might be a more intuitive way to generate the single item array(or even "xyz".ToCharArray()
for multiple single character delimiters). Should note that this means you are adding a bit of extra runtime processing but it is probably so small to be negligible.
You could create an (extension) method that had optional parameters.
public static string[] SplitDelimiter(this string str, char delimiter, int count = 0, StringSplitOptions options = StringSplitOptions.None)
{
int toCount = count == 0 ? count = str.Length : toCount = count;
return str.Split(new[] { delimiter }, toCount, options);
}
Then you can use it without creating an array explicitly.
string myString = "1,2,3";
Console.WriteLine(myString.SplitDelimiter(',').Count()); //returns 3
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