【问题标题】:string length and compare to int字符串长度并与 int 比较
【发布时间】:2018-05-11 04:21:21
【问题描述】:

为什么这不起作用? 例如,如果 teaserLength 返回 300,则为 true。 如果它返回例如 37,它是假的..即使它应该被反转......

我的代码:

@{
     int teaserLength = item.TeaserText.Length;
}
@if (teaserLength >= 75)
{
     @item.TeaserText
}
else { 
     @item.TeaserText.Substring(1, 75)
}

以及为什么一个长度为37的TeaserText,给一个

ArgumentOutOfRangeException
Index and length must refer to a location within the string.

在子字符串上?

【问题讨论】:

  • 因为你说的是​​if the teaserLength is smaller than 75, take the substring?
  • 子字符串从索引 0 开始。使用数组的方式相同。
  • @IanH。我不是说,如果 teaserText 小于或等于 75,请使用 Teaser 文本。 else if large use substring ?
  • 您是说如果 teaserText 小于 75,则从索引 1(即第二个特点)。你想要它做什么?
  • 您可以完全摆脱teaserLength 变量和if/else 并返回@item.TeaserText.Substring(0, Math.Min(item.TeaserText.Length, 75));

标签: c# substring string-length


【解决方案1】:

Substring 中的“起始”索引是从零开始的,如果长度为 75 或更多,您只需要子字符串:

@if (teaserLength >= 75)
{
     @item.TeaserText.Substring(0, 75)
}
else { 
     @item.TeaserText
}

或者只是

@item.TeaserText.Substring(0, Math.Min(teaserLength, 75))

【讨论】:

    【解决方案2】:

    另一种方法是使用Min 函数:

    @{
        int maxCharsToDisplay = Math.Min(item.TeaserText.Length, 75);
    }
    
    @item.TeaserText.Substring(0, maxCharsToDisplay);
    

    对于值小于 75 的情况,Min 将返回该长度;如果值更大,则返回75。您最多只能有 75 个字符。

    【讨论】:

      【解决方案3】:

      再次阅读您自己的if 声明。

      @if (teaserLength >= 75)
      {
           @item.TeaserText
      }
      else { 
           @item.TeaserText.Substring(1, 75)
      }
      

      “如果teaserLength 大于或等于 75,则使用文本,否则使用子字符串。”

      不能取长度小于75的字符串的长度为75的子字符串。

      要解决此错误,只需将 >= 运算符换成 < 运算符即可。

      另外,假设您要将字符串截断为 75 个字符,您可能希望将 .Substring(1, 75) 切换为 .Substring(0, 75)。 正如@RufusL 正确提到的那样,否则长度为 75 的字符串会出现异常。

      【讨论】:

      • 为什么不修正你的答案而不是仅仅指出你会得到一个例外?
      • @DStanley 我的回答有什么问题?我说明了可能导致错误的原因并提供了解决方案。
      • 这不是 (我也没有投反对票),但将索引修复合并到答案中而不是添加旁注会更完整。
      • @DStanley answer,您是指代码 sn-p 吗?答案中提供的 sn-p 与问题中的相同 - 我包含它只是为了让读者在阅读时意识到错误。
      【解决方案4】:

      另一种方法是使用 System.LinqTake 您想要的最大项目数 (75),然后使用 Concat 它们:

      string.Concat(item.TeaserText.Take(75));
      

      【讨论】:

        猜你喜欢
        • 2013-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-24
        • 1970-01-01
        • 2016-04-05
        相关资源
        最近更新 更多