I have the following C# code:
ArticleContent = ds1.Tables[0].Rows[i]["ArticleContent"].ToString();
if (ArticleContent.Length > 260)
{
ArticleContent = ArticleContent.Remove(ArticleContent.IndexOf('.', 250)) + "...";
}
The problem here is that I get this error message:
StartIndex cannot be less than zero.
Why and how can I fix it?
You are getting that error because there is no '.'
character on or after index 250, so IndexOf
returns -1
. You then try to remove the character at position -1
which gives you the error you are seeing.
Also realize that Remove
only removes one character at that position, not everything after that position. What I suspect you want is:
if (ArticleContent.Length > 260)
{
int lastPeriod = ArticleContent.LastIndexOf('.');
if(lastPeriod < 0)
lastPeriod = 257; // just replace the last three characters
ArticleContent = ArticleContent.Substring(0,lastPeriod) + "...";
}
That will add ellipses to the string, making sure it is no longer that 260 characters and breaking at a sentence if possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With