How to in C# keep a set number of letters for a string in console writeline

Dan picture Dan · Jan 6, 2013 · Viewed 6.9k times · Source

Ok so basically I want something like

Console.WriteLine(
    "{0}:   {1}/{2}hp    {3}/{4}mp   {5}", 
    character.Identifier, 
    character.CurrentHealth, 
    character.MaxHealth,
    character.CurrentMagic, 
    character.MaxMagic, 
    character.Fatigue
    );

and then have the character.Identifier (which is basically a name) have a set number of letters which it will replace with spaces if needed so that in might print

Josh:   20/20hp    20/20mp   3

or

J:      20/20hp    20/20mp   3

but the HP and then mp and everything else is always in line. I am aware that its probably one of the {0:} but i couldn't figure out one that works

Answer

WildCrustacean picture WildCrustacean · Jan 6, 2013

The second argument in the {0} notation can give you a fixed width field, so if you wanted the identifier (name) to always be 10 characters long and be left justified, you would use {0,-10}

MSDN is a good resource for this kind of question too, if you read the documentation for String.Format it has an example of a fixed width table that might be similar to what you want.

Also, as Hogan's answer correctly points out, you would have to append the : to the string outside of the format string if you want it right next to the name.