Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there String.Split() which takes StringComparison into account?

In Best Practices for Using Strings in the .NET Framework we are encouraged to supply proper StringComparison whenever we are comparing strings. I agree with the point but I see that unlike other methods, String.Split() actually does not have overloads with comparison parameter.

Is there equivalent of String.Split() taking string comparisons somewhere in the framework or am I expected to write my own?

like image 495
miroxlav Avatar asked Jan 07 '23 12:01

miroxlav


1 Answers

Is there equivalent of String.Split() taking string comparisons somewhere in the framework?

No. There is not. And frankly I don't think it makes a lot of sense. If you split a string on a special character, generally because another system supplied the original string to you, why would you want to split on X and x? Usually you don't want to, and .NET doesn't supply a method to help you with it.

Am I expected to write my own?

Well, you could use a little help. Here is a case insensitive splitter. It still needs some work, but you can use it as a starting point:

public static string[] Split(string s, params char[] delimeter)
{
    List<string> parts = new List<string>();

    int lastPartIndex = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (delimeter.Select(x => char.ToUpperInvariant(x)).Contains(char.ToUpperInvariant(s[i])))
        {
            parts.Add(s.Substring(lastPartIndex, i - lastPartIndex));

            lastPartIndex = i + 1;
        }
    }

    if (lastPartIndex < s.Length)
    {
        parts.Add(s.Substring(lastPartIndex, s.Length - lastPartIndex));
    }

    return parts.ToArray();
}
like image 192
Patrick Hofman Avatar answered Jan 10 '23 04:01

Patrick Hofman