比较大字符串内容

时间:2014-10-24 11:07:17

标签: c# .net string comparison

我实现了一个处理多种复杂数据的系统,我必须能够使用IComparable接口契约对给定内部值的数据对象进行排序。

其中一个对象类型处理短到很长(2 * 10 ^ 28)个字符串,具体化为TextReader。

有没有人知道以最佳方式在这些长对象上计算这种差异的有效方法?我似乎无法找到任何解决方案来确定两个对象之间的最大或相等,但只有文本差异算法。

1 个答案:

答案 0 :(得分:1)

由于它们被实现为TextReaders,我可能会使用这样的方法:

static int Compare(TextReader r1, TextReader r2)
{
     int c1 = 0, c2 = 0;

     // read one char at a time and compare them
     // until we reach end of one of the strings
     while((c1 = r1.Read()) != -1 && 
           (c2 = r2.Read()) != -1)
     {
          var result = ((char)c1).CompareTo((char)c2);
          if (result != 0) return result;
     }
     // if both are -1 then strings have the same length and 
     // consist of same chars so they are equal
     if (c1 == -1 && c2 == -1)
         return 0;
     // if r1 is subset of r2 then r2 is greater
     else if (c1 == -1)
         return -1;
     // otherwise r1 is greater
     else
         return 1;
}