我有以下C#代码:
ArticleContent = ds1.Tables[0].Rows[i]["ArticleContent"].ToString();
if (ArticleContent.Length > 260)
{
ArticleContent = ArticleContent.Remove(ArticleContent.IndexOf('.', 250)) + "...";
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是我收到此错误消息:
StartIndex不能小于零.
为什么以及如何解决它?
D S*_*ley 18
您收到该错误,因为'.'索引250上或之后没有字符,因此IndexOf返回-1.然后尝试删除位置-1上的字符,这会给出您看到的错误.
还要意识到Remove只删除该位置的一个字符,而不是该位置后的所有字符.我怀疑你想要的是:
if (ArticleContent.Length > 260)
{
int lastPeriod = ArticleContent.LastIndexOf('.');
if(lastPeriod < 0)
lastPeriod = 257; // just replace the last three characters
ArticleContent = ArticleContent.Substring(0,lastPeriod) + "...";
}
Run Code Online (Sandbox Code Playgroud)
这将为字符串添加省略号,确保它不再是260个字符,如果可能的话会破坏句子.