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

4.60/5 (5 votes)
23 Feb 2012CPOL 12.7K  
An Extension Method that is similar to String.StartsWith, but uses a StringComparer
Today I had the need of System.String.StartsWith, but I wanted to specify whether or not to be case insensitive. There is an overload that takes a value of System.StringComparison, but my method was already taking a System.StringComparer as a parameter, so it made more sense to use that. Here is what I devised:

namespace PIEBALD.Lib.LibExt.StartsWith
{
  public static partial class LibExt
  {
    public static bool
    StartsWith
    (
      this string           String1
    ,
      string                String2
    ,
      System.StringComparer Comparer
    )
    {
      return
      (
        ( String1.Length >= String2.Length )
      &&
        ( Comparer.Compare ( String1.Substring ( 0 , String2.Length ) , String2 ) == 0 )
      ) ;
    }
  }
}


Edit: I changed it to use System.Collections.Generic.IEqualityComparer<string>.

License

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