OdraEncoded

Numeric comparer

Nov 17th, 2012
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. public class NumericComparer : IComparer<string>
  2. {
  3.     #region IComparer implementation
  4.     public int Compare (string x, string y)
  5.     {
  6.         if (x == y)
  7.             return 0;
  8.  
  9.         int xi = 0;
  10.         int yi = 0;
  11.  
  12.         while (xi < x.Length && yi < y.Length) {
  13.             while(xi < x.Length && char.IsWhiteSpace(x[xi])) xi++;
  14.             while(yi < y.Length && char.IsWhiteSpace(y[yi])) yi++;
  15.  
  16.             if(char.IsDigit(x[xi]) && char.IsDigit(y[yi]))
  17.             {
  18.                 string xDigits = "";
  19.  
  20.                 do
  21.                 {
  22.                     xDigits += x[xi];
  23.                     xi++;
  24.                 }
  25.                 while(xi < x.Length && char.IsDigit(x[xi]));
  26.  
  27.                 string yDigits = "";
  28.  
  29.                 do
  30.                 {
  31.                     yDigits += y[yi];
  32.                     yi++;
  33.                 }
  34.                 while(yi < y.Length && char.IsDigit(y[yi]));
  35.  
  36.                 int xVal = ParseDigits(xDigits);
  37.                 int yVal = ParseDigits(yDigits);
  38.  
  39.                 if(xVal > yVal) return 1;
  40.                 else if (xVal < yVal) return -1;
  41.             }
  42.             else if(x[xi] != y[yi])
  43.             {
  44.                 return x[xi].CompareTo(y[yi]);
  45.             }
  46.             else
  47.             {
  48.                 xi++;
  49.                 yi++;
  50.             }
  51.         }
  52.  
  53.         return 0;
  54.     }
  55.  
  56.     public static int ParseDigits (string digits)
  57.     {
  58.         string newDigits = "";
  59.  
  60.         foreach (char c in digits) {
  61.             if (c >= '0' && c <= '9')
  62.                 newDigits += c;
  63.             else if (c >= '\uFF10' && c <= '\uFF19')
  64.                 newDigits += (char)(c - '\uFF10' + '0');
  65.             else if (c >= '\u0660' && c <= '\u0669')
  66.                 newDigits += (char)(c - '\u0660' + '0');
  67.             else if (c >= '\u09E6' && c <= '\u09EF')
  68.                 newDigits += (char)(c - '\u09E6' + '0');
  69.         }
  70.  
  71.         if (newDigits == "")
  72.             return 0;
  73.         else
  74.             return int.Parse (newDigits);
  75.     }
  76.     #endregion
  77. }
Advertisement
Add Comment
Please, Sign In to add comment