以与填充相似的样式格式化字符串

本文关键字:样式 格式化 字符串 相似 填充 | 更新日期: 2023-09-27 18:11:16

在我的程序中,我正在输出一个文本文件。在这个文本文件中,我经常在与我的数据相同的行上进行注释(通常只是一个数值)。有时,当数据变量的长度不同时,它会使注释不对齐。出于组织目的,如果我能格式化字符串,使注释总是从同一列开始,那将是有益的。

这是我的问题的一个例子(.txt文件输出):

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

现在我正在使用填充(它工作),但我不喜欢我必须计算所有字符串值的长度来计算填充它的长度。我不能使用字符串。长度,因为我要像这样输出数据:

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

我可以使用什么方法来确保无论字符串的长度如何,注释总是从同一列开始?

以与填充相似的样式格式化字符串

为什么不在第一个字段指定右填充呢?这将始终保持一致:

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

查看MSDN格式化字符串:

格式项

格式项的语法如下:{index[,align][:formatString]}

对齐

可选的。一个带符号的整数,指示将参数插入其中的字段的总长度,以及它是右对齐(正整数)还是左对齐(负整数)。如果省略对齐,则相应参数的字符串表示形式将插入没有前后空格的字段中。

的例子:

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);}
输出:

// 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 %