I recently posted some code that could have taken advantage of format strings available when using the ToString() for integer output.  The other day I was building a report for a moonlighting gig where some of the text had to be right aligned and left aligned.  String.Format() does that as well.  I've seen some goofy attempts at formatting text, presumably not realizing the makers of the framework built it in.

Check out the code below:

   1: var phone = "319-585-6594";
   2:  
   3: Console.WriteLine(string.Format("{0,20}", phone));    // right aligned
   4: Console.WriteLine(string.Format("{0,-20}", phone));   // left aligned

Which produces:

image

Next time you find yourself calculating lengths of strings and prepending/appending spaces and/or padding stop and take use of what is already provided for you.


 
Categories:

Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview