Connecting Tech Pros Worldwide Help | Site Map

Padding strings (System.Console.Write)

Newbie
 
Join Date: Oct 2009
Posts: 2
#1: Oct 6 '09
Hey all, a beginner at C# here.

I'm writing a console application in C# where i handle a lot of numerical data, and try to present them in a coherent, nicely aligned form.

I'm using System.Console.WriteLine

I have 8 - 10 columns of data for each record, each item per record contains 1 to 10 digits.

The problem i have is that i can't figure out how to align things. '\t' obviously wouldn't work well, because if you're on a tab boundary, it will screw things up.

I figured out that i could use the format specifier {0:d10} but that pads zeroes in front of each number, this is close to what i want

is there a way to do blank space padding instead of zero padding like with {0:d10}?

thanks for any help
Familiar Sight
 
Join Date: Jul 2009
Location: Calgary, Alberta, Canada
Posts: 211
#2: Oct 6 '09

re: Padding strings (System.Console.Write)


http://msdn.microsoft.com/en-us/library/92h5dc07.aspx

Try that? You can pad the string with spaces based on the length of the string.
Newbie
 
Join Date: Oct 2009
Posts: 2
#3: Oct 7 '09

re: Padding strings (System.Console.Write)


so i have to...


myvar.ToString().PadRight(10,' ') for each and every entry?

allright, i was hoping there was a nice format specifier, but i guess i have to bite the bullet.
Familiar Sight
 
Join Date: Jul 2009
Location: Calgary, Alberta, Canada
Posts: 211
#4: Oct 7 '09

re: Padding strings (System.Console.Write)


Oh, there might be, I just don't know of it :D

I did a google, is this what you're looking for?
http://blog.stevex.net/string-formatting-in-csharp/

... I'm not sure that it is.
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,148
#5: Oct 7 '09

re: Padding strings (System.Console.Write)


You want them RIGHT padded? Odd.
Left padding is very easy to do:
Expand|Select|Wrap|Line Numbers
  1. int dd = 4531;
  2. string s=string.Format("{0,10}",dd);
  3.  
Reply