I am trying to extract the first 200 words of a string and sometimes I get the following error:
"Index and length must refer to a location within the string. Parameter name: length"
The code is:
int i = GetIndex(fullarticle, 200);
string result = fullarticle.Substring(0, i);
How do I fix this?
It appears safe to assume the error is coming from string.Substring. Given that you get this error when
startIndex + length > given.LengthorstartIndex < 0orlength < 0,GetIndexis either returning a value greater thanfullarticle.Lengthor a negative number. The error exists inGetIndexso if you wish to carry on with the code you have, you should post the code ofGetIndexto get the best answer.If you’re up for something different, you could try this: