【问题标题】:ASP.NET MVC SubString helpASP.NET MVC 子字符串帮助
【发布时间】:2011-01-05 23:14:42
【问题描述】:

我有一个显示新闻文章的 ASP.NET MVC 应用程序,对于主要段落,我有一个截断和 HTML 标记剥离器。例如<p><%= item.story.RemoveHTMLTags().Truncate() %></p>

这两个函数来自一个扩展,如下:

public static string RemoveHTMLTags(this string text)
{
    return Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
}
public static string Truncate(this string text)
{
    return text.Substring(0, 200) + "...";
}

但是,当我创建一篇新文章说一个只有 3-4 个单词的故事时,它会抛出这个错误:Index and length must refer to a location within the string. Parameter name: length

有什么问题?谢谢

【问题讨论】:

  • 在 164 次观看中,我不是唯一一个发现这个话题有用并因此投票赞成的人

标签: asp.net-mvc


【解决方案1】:

将您的截断函数更改为:

public static string Truncate(this string text) 
{     
    if(text.Length > 200)
    {
        return text.Substring(0, 200) + "..."; 
    }
    else
    {
        return text;
    }

} 

一个更有用的版本是

public static string Truncate(this string text, int length) 
{     
    if(text.Length > length)
    {
        return text.Substring(0, length) + "..."; 
    }
    else
    {
        return text;
    }

} 

【讨论】:

    【解决方案2】:

    问题是你的length参数比字符串长,所以是throwing an exception just as the function documentation states

    换句话说,如果字符串不是 200 个字符长,Substring(0, 200) 就不起作用。

    您需要根据原始字符串的长度动态确定子字符串。试试:

    return text.Substring(0, (text.Length > 200) : 200 ? text.Length);
    

    【讨论】:

    • 好吧,我该如何解决?基本上希望它应该做的是截断超过 200 个字符的故事。如果它们小于 200,则不应截断它。
    猜你喜欢
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2011-05-05
    • 2011-01-31
    相关资源
    最近更新 更多