winforms 解决异常的“超出范围”错误行为

wi3ka0sx  于 2022-12-04  发布在  其他
关注(0)|答案(2)|浏览(118)

我正在创建C# winforms应用程序,它必须在文件中找到字符串的所有示例,裁剪其间的文本,然后进行一些处理。
文本文件具有以下格式:
----密钥字符串----
要裁剪的文本1
----密钥字符串----
要裁剪的文本2
----密钥字符串----
要裁剪的文本3
基本上,我从该文件中裁剪“text 1”、“text 2”和“text 3”。
下面是执行上述操作的代码:

string contents = "";
MatchCollection matches;
using (StreamReader reader = File.OpenText(filepath))
{
    contents = reader.ReadToEnd();
    matches = Regex.Matches(contents, "Key_String");
}
int totalmatchcount = matches.Count;

for (int i = 0; i < totalmatchcount; i++ )
{
    int indd1 = matches[i].Index;
    int indd2 = 0;
    string sub_content = "";
    if (i != totalmatchcount - 1)
    {
        indd2 = matches[i+1].Index;
        try
        {
            sub_content = contents.Substring(indd1, indd2); // error here
        }
        catch
        {
            MessageBox.Show("Index 1: "  + indd1 + "\n" +
                "Index 2: "  + indd2 + "\n" +
                "Max index (length - 1): "  + (contents.Length - 1)
                );
        }
    }
    else { sub_content = contents.Substring(indd1); }
    // do some stuff with "sub_content"
}

它对我的一些文件工作得很好,但在某些情况下-我得到以下错误:
索引和长度必须引用字符串中的位置。参数名:长度
这很奇怪,因为我裁剪的子字符串位于主字符串的内部,而不是你猜的外部。我可以用“try-catch”输出证明这一点:
索引1:3211
指数2:4557
最大索引(长度-1):5869
如您所见-我没有裁剪位于索引范围之外的内容,那么问题是什么呢?
另外,我在谷歌上搜索过解决方案,但基本思路都是-“错误的索引”。在我的情况下-索引是“在”范围之内。嗯,至少我是这么认为的。

编辑

类似于以下内容的操作应该可以解决问题:

public string SubstringFix(string original, int start, int end)
    {
        int endindex = 0;
        if (end < original.Length)
        {
            endindex = end;
        }
        else
        {
            endindex = original.Length - 1;
        }

        return original.Substring(start, (end - start));
    }
xdnvmnnf

xdnvmnnf1#

Substring不接受两个索引。它接受一个索引和一个长度。您可能需要

indd2 - indd1

作为第二个参数(并检查该表达式是否存在“差一”错误)。

ou6hu8tu

ou6hu8tu2#

用你所拥有的,这就是你所得到的

3211+4557 = 7768

并且大于串的长度。
这就是子字符串的工作原理

substring(startindex, length)

字符串的长度不应小于startIndex + length

相关问题