This alternative is not substantially different, it simply splits the function into two:
- one for clipping
- one for comparing
public static string ExtClipRight(this string a, int n)
{
return (n < 0 || a.Length <= n) ? a : a.Substring(0, n);
}
...
public static bool ExtStartsWith(this string a, string b, IEqualityComparer<string> cmp)
{
return cmp.Equals(a.ExtClipRight(b.Length), b);
}
I have on several occasions the need of a "tolerant" substring access, most of the time in the form of clipping (get the string that is at most n chars long). That's why I reuse that clipping here.
Edit: I've taken Equals
instead of Compare
... and IEqualityComparer<string>
...