简体   繁体   中英

Formatting a string in a similar style to padding

In my program I am outputting a text file. In this text file I often have comments on the same lines as my data (usually just a numerical value). Sometimes when the data variable is of a different length it makes it so that the comments don't line up. For organizational purposes it would be beneficial if I could format the string so that the comments always start on the same column.

This is an example of my problem (.txt file output):

//Because of the extra number in the second value, the comments don't line up
5           ; First Data Value
12           ; Second Data Value

Right now I am using padding (and it works), but I don't like that I have to count the length of all of my string values to figure out how much to pad it. I cannot use string.Length because I am outputting my data like so:

StreamWriter.WriteLine(dataVal1 + "; First Data Value".PadLeft(29, ' '));
StreamWriter.WriteLine(dataVal2 + "; Second Data Value".PadLeft(30, ' '));

What method can I use to make sure that no matter the length of my string, the comments always start at the same column?

Why not specify a right-padding on the first field instead, which will always be consistent:

file.WriteLine(String.Format("{0,-30}; {1}", dataVal1, "First Data Value"));
file.WriteLine(String.Format("{0,-30}; {1}", dataVal2, "Second Data Value"));

See the MSDN FORMATING STRING :

The format item

A format item has this syntax: { index[,alignment][ :formatString] }

Alignment

Optional. A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.

Example:

foreach (var city in cities) {
     output = String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
                            city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
                            (city.Item5 - city.Item3)/ (double)city.Item3);
     Console.WriteLine(output);}

Output:

// The example displays the following output: 
//    City            Year  Population    Year  Population    Change (%) 
//     
//    Los Angeles     1940   1,504,277    1950   1,970,358        31.0 % 
//    New York        1940   7,454,995    1950   7,891,957         5.9 % 
//    Chicago         1940   3,396,808    1950   3,620,962         6.6 % 
//    Detroit         1940   1,623,452    1950   1,849,568        13.9 %

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM