【问题标题】:Substring Maximum Length子串最大长度
【发布时间】:2016-01-19 14:37:35
【问题描述】:

我有长度超过 150 个字符的字符串。我想删除前 17 个字符并保留其余字符。我在 ASP.net 4.5 中使用 Substring 方法,但在 str0 处收到错误消息:“System.ArgumentOutOfRangeException”。

 public static string extract(string dirinfo)
 {
      Int32 lensub = Convert.ToInt32(dirinfo.Length);
      string str0 = dirinfo.Substring(17, lensub);
      return str0;
 } 

【问题讨论】:

  • 这是因为Substring(17, lensub) 表示从第 17 个字符开始,然后向前移动与字符串全长相同的空格数。显然,从最后 17 个字符开始,您现在“超出范围”。试试Substring(17, lensub - 17);

标签: c# asp.net string substring asp.net-4.5


【解决方案1】:

Substring(int, int) 重载将长度作为您想要 rest 的第二个参数,如您所说,而不是完整的字符串长度。

如果你的字符串长度为 150,dirinfo.Substring(17, 150) 表示;

从 17 开始,因为位置蚂蚁在 之后需要 150 个字符。

这意味着,您的字符串需要167 字符至少,但它不需要。这就是为什么你会得到ArgumentOutOfRangeException

只需将Substring(int) overload 用作;

string str0 = dirinfo.Substring(17);

描述的;

从此实例中检索子字符串。子字符串开始于 指定字符位置并继续到字符串的末尾

顺便说一句,Length已经int,你不需要解析它。

【讨论】:

  • @Steve 但你快了 33 秒 :)
【解决方案2】:

您应该从计算的 len 中删除常数 17

 public static string extract(string dirinfo)
 {
      Int32 lensub = Convert.ToInt32(dirinfo.Length);
      string str0 = dirinfo.Substring(17, lensub-17);
      return str0;
 } 

否则需要返回的字符数超过字符串的剩余长度

当然,(感谢answer from Soner Gönül)您可以将方法简化为

 public static string extract(string dirinfo)
 {
      return (dirinfo.Length > 17 ? dirinfo.Substring(17) : "");
 } 

【讨论】:

    【解决方案3】:
    string str0 = dirinfo.Substring(17, lensub-17);
    return str0;
    

    【讨论】:

    • 字符串 str0 = dirinfo.Substring(17, lensub-17);返回 str0;
    【解决方案4】:

    我想删除17个字符并保留其余的。

    然后做你想做的事

    string str0 = dirinfo.Remove(0, 17);
    

    参考:String.Remove Method (Int32, Int32)

    public string Remove(int startIndex, int count)
    

    返回一个新字符串,其中当前实例中从指定位置开始的指定数量的字符已被删除

    【讨论】:

      猜你喜欢
      • 2016-11-17
      • 2016-06-14
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 2013-04-12
      • 2013-08-15
      • 2016-05-03
      • 1970-01-01
      相关资源
      最近更新 更多