String.Format() with max chars?

  • Thread starter Thread starter MC
  • Start date Start date
M

MC

Is it possible to use String.Format and a format specifier in such a
way to ensure that a string does not exceed the field width in which
it is placed?

Example:

string [] strings = {"Hello World", "Wednesday Evening", "Hi"};
string output;

foreach(string str in strings)
{
output = String.Format("{0,-4:???}", str);
}

The -4 ensures that str is placed into a field width 4 characters
wide, left justified--great!

What does ??? have to be so that str never exceeds 4 characters--so
that the output is:

Hell
Wedn
Hi

This can be done in C with printf(), so I thought it would be possible
in .NET.

Thanks,
Craig
 
MC said:
Is it possible to use String.Format and a format specifier in such a
way to ensure that a string does not exceed the field width in which
it is placed?
There is no built-in IFormatProvider for this, but you could build one
yourself. There are easier solutions available, the code below creates
fixed length strings.

foreach(string str in strings)
{
output = str.Substring(0,(str.Length>=4?4:str.Length)).PadRight(4);
}

Anders Norås
http://dotnetjunkies.com/weblog/anoras/
 
Back
Top