Problem with StripPreviewText() from the Public Templates

Vote:
 

I'm using the StripPreviewText-function from the Public Templates to show a preview of a number of articles, however it sometimes crash on the row previewText = previewText.Substring(0, previousWord); and at these moments the previousWord is -1. Any ideas of what could cause the problem? I'm not sure what the row before the if, setting the value of previousWord, does. 

 

 

/// <summary>
/// Strips a text to a given length without splitting the last word.
/// </summary>
/// <param name="previewText">The string to shorten</param>
/// <returns>A shortened version of the given string</returns>
private static string StripPreviewText(string previewText, int maxLength)
{
    if (previewText.Length <= maxLength)
    {
        return previewText;
    }
    previewText = previewText.Substring(0, maxLength);
    // The maximum number of characters to cut from the end of the string.
    int maxCharCut = (previewText.Length > 15 ? 15 : previewText.Length - 1);
    int previousWord = previewText.LastIndexOfAny(new char[] { ' ', '.', ',', '!', '?' }, previewText.Length - 1, maxCharCut);
    if (previousWord <= 0)
    {
        previewText = previewText.Substring(0, previousWord);
    }
    return previewText + " ...";
}

 

#36602
Feb 04, 2010 8:57
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.