【问题标题】:System.ArgumentOutOfRangeException: startIndex cannot be larger than length of stringSystem.ArgumentOutOfRangeException:startIndex 不能大于字符串的长度
【发布时间】:2012-03-21 21:19:06
【问题描述】:

我有这个代码。我正在尝试仅检索文本“第一个程序”。考虑到我知道索引是 25,字符串的总长度是 35。

string text="Hello world ! This is my first program";

Response.Write(text.SubString(25,35));

但我在运行时收到错误“System.ArgumentOutOfRangeException:startIndex 不能大于字符串长度”

【问题讨论】:

  • 第二个参数不是应该是子串的长度吗?
  • 请注意,您还需要正确设置长度参数 - 如果 start+lengthToExtract > 字符串的实际长度,您将得到 ArgumentOutOfRangeException - 请参阅msdn.microsoft.com/en-us/library/aka44szs.aspx。你可能想要的是 text.SubString(25, 13) - 13 是文本“第一个程序”的长度
  • 有趣。我得到一个 ArgumentOutOfRangeException,但有以下消息:“索引和长度必须引用字符串中的位置。参数名称:长度”

标签: c# asp.net-mvc


【解决方案1】:

String.Substring的参数为:

public string Substring(int startIndex, int length)

您尝试在第 26 个字符(startIndex 从零开始)之后 取 35 个字符,这超出了范围。

如果您只想从第 25 个字符到字符串末尾,请使用 text.SubString(24)

【讨论】:

    【解决方案2】:

    string.Substring() 的第二个参数是 长度,而不是结束偏移:

    Response.Write(text.Substring(25, 10));
    

    【讨论】:

      【解决方案3】:

      SubString 的第二个参数是子字符串中的字符数。

      更简单的方法。

      int startIndex = 25; // find out startIndex
      int endIndex = 35;   // find out endIndex, in this case it is text.Length;
      int length = endIndex - startIndex; // always subtract startIndex from the position wherever you want your substring to end i.e. endIndex
      
      // call substring
      Response.Write(text.Substring(startIndex,length));     
      

      您可以执行一些操作或调用函数来获取开始/结束索引值。使用这种方法,您就不太可能遇到与索引相关的任何问题。

      【讨论】:

        【解决方案4】:

        Substring 的第二个参数是您希望子字符串的长度,而不是子字符串的终点。 25 + 35 超出了原字符串的范围,所以会抛出异常。

        【讨论】:

          【解决方案5】:

          这段时间你可以使用

          (LINQ ElementAt)(ElementAtOrDefault) 方法。但是,当指定索引为负值或不小于序列大小时,ElementAt 扩展方法会抛出 System.ArguementOutOfRangeException

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-02
            • 1970-01-01
            • 2020-05-03
            • 2013-07-20
            相关资源
            最近更新 更多