Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StartIndex cannot be less than zero. - Error when trying to change a string

Tags:

string

c#

.net

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?

like image 531
Nave Tseva Avatar asked Jun 24 '13 18:06

Nave Tseva


1 Answers

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.

like image 62
D Stanley Avatar answered Sep 27 '22 21:09

D Stanley