我有一个HTML应用程序,可以显示新闻文章,对于主要段落,我有一个截断和ASP.NET标签剥离器。例如<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
有什么问题吗?谢谢
发布于 2011-01-06 07:17:36
将truncate函数更改为:
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;
}
} 发布于 2011-01-06 07:16:58
问题是长度参数比字符串长,所以它是throwing an exception just as the function documentation states。
换句话说,如果字符串长度不超过200个字符,Substring(0, 200)就不起作用。
您需要根据原始字符串的长度动态确定子串。尝试:
return text.Substring(0, (text.Length > 200) : 200 ? text.Length);https://stackoverflow.com/questions/4610199
复制相似问题