Work with a bulky string.

The .Split () string in .NET can be cumbersome to use. With many overloads, you must specify an array even when passing one separator (in fact, only one overload is marked with parameters).

Is there such an alternative? Is there any way to complete the task without creating arrays.

+4
source share
2 answers

The problem 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):

  • The parameter paramscan / should be displayed as the last parameter.
  • Function overloads must support the same order of parameters.

So, you have the first overload:

Split(params char[] separator)

params , , .

, separator , params, .

, . params , , .

, separator params. , :

public string[] Split(int count, StringSplitOptions options, params char[] separator)

, API. , params , .

Alternative

, Craig W. , "x".ToCharArray() ( "xyz".ToCharArray() ). , , , , , , .

+3

() , .

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);
}

.

string myString = "1,2,3";
Console.WriteLine(myString.SplitDelimiter(',').Count()); //returns 3
+2

All Articles