String.format???

  • Thread starter Thread starter Anders M
  • Start date Start date
A

Anders M

Hi!

I'd like to format a string as follows:

hi my name is anders and I'm programming
to:
hi my name...

The formatting should shorten the text to at most 10 chars and add "..." in
the end.

Is that possible with String.Format?

/Anders
 
The elipses will be placed automatically if you use the
StringFormat.Trimming property and the StringTrimming EllipsisCharacter
enumeration. The string trimming happens when you try and output a string
into a rectangle that's too small for the string. Use DrawString and specify
a bounding rectangle for the string.


--
Bob Powell [MVP]
Visual C#, System.Drawing

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 
Well, not quite. The quick 'n' dirty solution would be:

string trimmedText;
if (text.Length > 10)
{
trimmedText = text.Substring(0, 10) + "...";
}
else
{
trimmedText = text;
}

or, if you want to be _really_ quick 'n' dirty, you could use the
ternary operator (ewww):

string trimmedText = text.Length > 10 : text.Substring(0,10) + "..." :
text;
 
Back
Top