Click here to Skip to main content
11,505,158 members (68,754 online)
Click here to Skip to main content

Tagged as

A String.StartsWith that uses a StringComparer

, 24 Feb 2012 CPOL 3.5K
Rate this:
Please Sign up or sign in to vote.
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>...

License

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

Share

About the Author

Andreas Gieriet
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).
Follow on   LinkedIn

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
memberPIEBALDconsult24-Feb-12 2:59 
GeneralYes, but won't it still do the Compare even if a is shorter ... Pin
PIEBALDconsult24-Feb-12 2:09
memberPIEBALDconsult24-Feb-12 2:09 
GeneralRe: It's functional equivalent to your StartsWith(...) function,... Pin
Andreas Gieriet24-Feb-12 2:28
memberAndreas Gieriet24-Feb-12 2:28 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 24 Feb 2012
Article Copyright 2012 by Andreas Gieriet
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid