Click here to Skip to main content
15,881,424 members
Articles / General Programming / String
Alternative
Tip/Trick

A String.StartsWith that uses a StringComparer

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
24 Feb 2012CPOL 10.1K   3
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)


Written By
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.

More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).

Comments and Discussions

 
GeneralRe: I don't think I'd be concerned with that even if I thought i... Pin
PIEBALDconsult24-Feb-12 2:59
mvePIEBALDconsult24-Feb-12 2:59 
GeneralYes, but won't it still do the Compare even if a is shorter ... Pin
PIEBALDconsult24-Feb-12 2:09
mvePIEBALDconsult24-Feb-12 2:09 
GeneralRe: It's functional equivalent to your StartsWith(...) function,... Pin
Andreas Gieriet24-Feb-12 2:28
professionalAndreas Gieriet24-Feb-12 2:28 
It's functional equivalent to your StartsWith(...) function, except that it does the comparison in any case. I leave that decision to the comaprer if it's worth to compare.

Comparing instead of checking for equality is anyways more expensive since more logic is involved in detecting -1, 0, +1 instead of equal=yes/no.

So, if you are concerned about performance, I'd suggest to use equality instead of comparison.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.