【问题标题】:solving unusual "out of range" error behavior解决异常的“超出范围”错误行为
【发布时间】:2012-08-18 14:09:45
【问题描述】:

我正在创建 C# winforms 应用程序,它必须查找文件中所有出现的字符串,裁剪中间的文本,然后进行一些处理。

文本文件格式如下:

---- Key_String ----

要裁剪的文本 1

---- Key_String ----

要裁剪的文本 2

---- Key_String ----

要裁剪的文本 3

基本上我会从该文件中裁剪“text1”、“text2”、“text3”。

这是执行上述操作的代码:

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));
    }

【问题讨论】:

    标签: c# winforms text find-occurrences


    【解决方案1】:

    Substring 不需要两个索引。它需要一个索引和一个长度。也许,你想要

    indd2 - indd1
    

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

    【讨论】:

    • 哎呀,我的错;(我从没想过会失败这么多。对不起,显然是愚蠢的问题..并向您的代表 +1。
    • @Alex 不要感觉太糟糕。 Substring 跨语言的实现往往会有所不同。当我拨打Substring 时,我仍然偶尔需要停下来记住我想要的是长度还是 EndIndex。
    • 只是补充一点,一些 语言似乎想和你玩心理战,并且有两种实现方式,但名称只有轻微的模棱两可的变化。 JavaScript 例如:xpertdeveloper.com/2012/01/substr-vs-substring-javascript
    【解决方案2】:

    你所拥有的就是你所得到的

    3211+4557 = 7768
    

    并且大于字符串的长度。

    这就是子字符串的工作原理

    substring(startindex, length)
    

    字符串长度不小于startIndex + length

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      相关资源
      最近更新 更多