How can you format a string to a fixed length?

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.
 
G

Guest

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
 
M

Marc Gravell

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
 
G

Guest

Yep,

I forgot to mention that there is no apropriate StringFormat, and of course
Substring "rock" more!
 
J

John Dinning

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,
 
G

Guest

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

All the best,

Martin
 

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