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