Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#4.0

Sorting Strings Based on the Position of the Block Letter

0.00/5 (No votes)
6 Jun 2012CPOL 15.5K  
This is an alternative for Sorting Strings based on the position of the block letter

Introduction

Here's an IComparer that implements the spec as I understand it. It uses a Regular Expression to find the indices of the first uppercase letters.

C#
namespace PIEBALD.Types
{
  public sealed class WackyComparer : System.Collections.Generic.IComparer<string>
  {
    private static readonly System.Text.RegularExpressions.Regex reg ;
    
    static WackyComparer
    (
    )
    {
      /* A Regex to find an uppercase letter */
      reg = new System.Text.RegularExpressions.Regex ( "[A-Z]" ) ;

      return ;
    }

    public int
    Compare
    ( 
      string Op0
    ,
      string Op1
    )
    {
      int result = 0 ;

      /* Null protection left as an exercise */

      System.Text.RegularExpressions.Match mat ;

      /* If the Regex matches the strings, then use the indices, else Max */
      int index0 = ( mat = reg.Match ( Op0 )).Success ? mat.Index : System.Int32.MaxValue ;
      int index1 = ( mat = reg.Match ( Op1 )).Success ? mat.Index : System.Int32.MaxValue ;

      /* Compare the indices, if equal compare the strings as normal */
      if ( ( result = index0 - index1 ) == 0 )
      {
        result = Op0.CompareTo ( Op1 ) ;
      }

      return ( result ) ;
    }
  }
}

License

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