我用C#编写了一个程序来比较两个非常长的字符串(10 000 000)。
代码是这样的:
// sample strings for you:
string test1 = new string('A',100000000), test2 =new string('A',100000000);
int i = 0, interval = 100000, size = test1.Length;
if (test1.Length != test2.Length)
{
return;
}
else
{
while(i + interval < size){
if (test1.Substring(i, i + interval) == test2.Substring(i, i + interval))
{
//TO DO
}
else
{
Console.WriteLine(i);
}
i += interval;
}
当i=5 400 000时,在mscorlib.dll中发生类型为"System.ArgumentOutOfRangeException"的未处理异常。
为什么会发生这种情况?
参见此行:
if (test1.Substring(i, i + interval) == test2.Substring(i, i + interval))
根据文件,String.Substring
的第二个论点是:
length(System.Int32):子字符串中的字符数
您正在使用它作为"要检索的最后一个索引"。根据这些相同的文档,如果:,则抛出ArgumentOutOfRangeException
startIndex plus length indicates a position not within this instance.
-or-
startIndex or length is less than zero.
进行到一半时,您将检索Substring(test1.length / 2, (test1.length / 2) + interval)
,使第一个条件为true,一旦您完成了字符串的一半,这符合您提到的1000多万个字符串的540万标记。
管理摘要:您不应该将i
添加到Substring
调用的第二个参数中。