c# - 如何在C#中调试System.ArgumentOutOfRangeException错误?

标签 c# error-handling outofrangeexception

该代码应该获取两个样本(一个原始样本和一个新样本),然后确定已插入到第一个序列中的最小单个连续片段的长度。

尝试一些样本时,出现以下错误消息:

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/

相关文章:

c# - 写入文件 ASP.NET C# 之后不锁定它们

读取 ExcelWorksheet 时出现 C# ArgumentOutOfRangeException

C++ vector::_M_range_check 错误?

c# - Azure 函数 - 我们什么时候需要使用 out 进行输出绑定(bind)?

c# - LUIS 获取所有意图列表,其中包含所有标记的话语

php - PHP登录文件不起作用。继续返回登录页面而不是用户个人资料

javascript - node.js 中有问题的 socket.parser.resume() 错误

sql - VBA Excel错误将nvarchar值转换为int

允许有空格的 Java 列表

c# - 为什么我的游戏中蛇的中间部分有时会消失?