Click here to Skip to main content
13,142,182 members (51,949 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.6K views
Posted 24 Feb 2012

A String.StartsWith that uses a StringComparer

, 24 Feb 2012
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).

You may also be interested in...

Pro
Pro

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

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