How can you format a string to a fixed length?

  • Thread starter Thread starter John Dinning
  • Start date Start date
J

John Dinning

In 'C' it was possible to format a string to a fixed length, e.g. to 10
characters:

printf("%10.10s","123456789012345"); would return "1234567890", and

printf("%10.10s","12345"); would return " 12345"

I can find no easy way to do this using string.format in C#.

It is possible to set a minumum length e.g.
string.format("{0,10:s}",12345"); will return a string 10 chars long,
but not a maximum - or am I missing something?
Any help welcome.

John.
 
Hello,

I think the Remove method will do a good job here.
int numberofchars = 10;
string test = "dnjghnhnkfdnjkwenfkj";
string only10chars = test.Remove(numberofchars, test.Length-numberofchars);

All the best,

Martin
 
If I read correctly, the OP wanted a "string.Format()" format
specifier to do this in-place; AFAIK none such exists.

Re getting the trimmed version separately:

string only10chars = test.Substring(0,10);

is probably easier to understand (and therefore debug)...

Marc
 
Yep,

I forgot to mention that there is no apropriate StringFormat, and of course
Substring "rock" more!
 
Thanks for the suggestions.
I was hoping that I had missed something in string.format.
It seems a backward step (more code required) to have to use substring or
remove, but so be it.

Thnaks again,
John,
 
You could make a nice static function with two parameters and a return value.
Then it should akso look clean!

All the best,

Martin
 
Back
Top