mercoledì 12 giugno 2013

Extract the first characters of a text.

Good morning to everybody

What I propose today is a simple function to extract the first characters of a text.
Even in this simple function we have some requirements:

  • must be extracted whole words only.
  • if the text exceeds the size you want, we have to append some points of suspension.
  • the suspension points contribute to the number of desired characters.

Here's the function:


  public string GetAbstract(string text, int maxCharacters)
        {
            if (String.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else    if (text.Length < maxCharacters)
            {
                return text;
            }
            else
            {
                string textToEsamine = text.Substring(0, maxCharacters);

                int lastSpacePosition = textToEsamine.LastIndexOf(" ", textToEsamine.Length);

                if (lastSpacePosition > 0)
                {
                    return textToEsamine.Substring(0, lastSpacePosition) + "...";
                }
                else
                {
                    /* devo troncare la parola */
                    return textToEsamine.Substring(0, maxCharacters - 3) + "...";
                }
            }
        }



If we really want to esagereare we can also create an extension method for object "String".
In this way we can easily extract text from each string.


public static class Extensions
    {
  public static string GetAbstract(this string text, int maxCharacters)
        {
            if (String.IsNullOrEmpty(text))
            {
                return string.Empty;
            }
            else    if (text.Length < maxCharacters)
            {
                return text;
            }
            else
            {
                string textToEsamine = text.Substring(0, maxCharacters);

                int lastSpacePosition = textToEsamine.LastIndexOf(" ", textToEsamine.Length);

                if (lastSpacePosition > 0)
                {
                    return textToEsamine.Substring(0, lastSpacePosition) + "...";
                }
                else
                {
                    /* devo troncare la parola */
                    return textToEsamine.Substring(0, maxCharacters - 3) + "...";
                }
            }
        }
}

Enjoy!

Nessun commento:

Posta un commento