String.Format() with max chars?

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
 
?

=?ISO-8859-1?Q?Anders_Nor=E5s?=

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/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top