Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / programming / string

A String.StartsWith that uses a StringComparer

0.00/5 (No votes)
24 Feb 2012CPOL 10.4K  
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

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)