Insert suffix like “…” or “more” in the end of the text using c#

September 21, 2011

tags: , ,
no comments

Hi guys,


One of ours clients wanted a generic method that include some


kind of suffix like “…” or “more” if the content turned out to be longer than the


short description allows.


in our solution it was important to shorten the text ,


NOT in the middle of the word  but after the last space .


Bad example


our text: Hello World my name is Alex.


result text: Hello World my na


Good example


our text: Hello World my name is Alex.


result text: Hello World my name


that is exactly what this method does.


it takes as parameter the text, the suffix and the maximum number of chars


and return the new text with the suffix.


//substrings the text by the number of chars and

//returns the new text with suffix

 private string GetsuffixString(string text, int charNumber, string suffix)

{

 string resultText = string.Empty;

 string newString = string.Empty;

 string suffixString = suffix;  //suffix like “…” or “more”

 int lastSpaceCountHolder = 0;

 

 for (int i = 0; i < text.Length; i++)

 {

     if (text[i] == ‘ ‘)

     {

         spaceCountHolder=i;

     }

     //insert the suffix else return the origenal text

     if (i >= charNumber)

     {

        //if the char is space then substring it

         if (text[i] == ‘ ‘)

         {

            newString = text.Substring(0,i);

            resultText = NewString.Insert(newString.Length, suffixString);

         }

         //substring from the last space

         else if (lastSpaceCountHolder!= 0)

         {

            newString = text.Substring(0,lastSpaceCountHolder);

            resultText = NewString.Insert(newString.Length, suffixString);

         }               

         //we have no choice, cut in the end of the chars length

         else

         {

            newString = text.Substring(0,charNumber);

            resultText = NewString.Insert(newString.Length, suffixString);

         }

            return resultText;

      }

   }

            return text;     

  }

 


That’s all folks…


Hope this post help.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*