65.9K
CodeProject is changing. Read more.
Home

A String.StartsWith that uses a StringComparer

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Feb 24, 2012

CPOL
viewsIcon

10441

This alternative is not substantially different, it simply splits the function into two:one for clippingone for comparingpublic static string ExtClipRight(this string a, int n){ return (n < 0 || a.Length <= n) ? a : a.Substring(0, n);}...public static bool...

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>...