该代码应该获取两个样本(一个原始样本和一个新样本),然后确定已插入到第一个序列中的最小单个连续片段的长度。
尝试一些样本时,出现以下错误消息:
System.ArgumentOutOfRangeException: 'Index and length must refer to a place within the string. Parameter name: length
这是代码:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetSample());
Console.ReadKey();
}
public static int GetSample()
{
string sample1 = Console.ReadLine();
string sample2 = Console.ReadLine();
if (sample1 == sample2) return 0;
if (sample1.Length >= sample2.Length)
{
for (int i = 0; i < sample2.Length; i++)
{
if (!(sample1[i] == sample2[i]))
{
sample1 = sample1.Substring(i, sample1.Length);
sample2 = sample2.Substring(i, sample2.Length);
break;
}
}
int var = sample1.Length - sample2.Length;
for (int i = sample2.Length - 1; i >= 0; i--)
{
if (sample2[i] == sample1[i + var])
sample2 = trimlast(sample2);
}
}
else
{
for (int i = 0; i < sample1.Length; i++)
{
if (!(sample1[i] == sample2[i]))
{
sample1 = sample1.Substring(i, sample1.Length);
sample2 = sample2.Substring(i, sample2.Length);
break;
}
}
int var = sample2.Length - sample1.Length;
for (int i = sample1.Length - 1; i >= 0; i--)
{
if (sample2[i + var] == sample1[i])
sample2 = trimlast(sample2);
}
}
return sample2.Length;
}
public static string trimlast(string str)
{
return str.Substring(0, str.Length - 1);
}
}
}
最佳答案
问题是:
sample1 = sample1.Substring(i, sample1.Length);
和其他类似的方法调用。
Substring
的第二个参数是长度(即要为子字符串检索的字符数)。因此,如果i
大于0,则在这种情况下它将失败,因为该方法将尝试检索字符串中没有的字符。
关于c# - 如何在C#中调试System.ArgumentOutOfRangeException错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50220519/