martedì 11 giugno 2013

Estrarre le prime lettere di un testo

Buongiorno a tutti.

Quello che vi propongo oggi è una semplice funzione per estrarre i primi caratteri di un testo.
Anche in una funzione così semplice debbono essere tenuti presenti alcuni requisiti:


  • devono essere estratte solo parole intere
  • se il testo supera la grandezza desiderata devono essere accodati dei punti di sospensione.
  • i punti di sospensione concorrono al conto del numero di caratteri



Ecco la funzione:



  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) + "...";
                }
            }
        }



Se vogliamo proprio esagereare possiamo anche crearne un extension method per l'oggetto "String".
In questo modo possiamo estrarre un testo da ogni stringa.


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) + "...";
                }
            }
        }
}

Divertitevi!

Nessun commento:

Posta un commento