使用字符串插值将字符串格式化为列
Formatting a string into columns using String Interpolation
我需要打印双精度数,以便为值的字符串表示分配一定数量的符号(如 8)。接下来的单词应该从每个字符串中字符串开头的相同索引开始。现在我有:
value: 0 test
value: 0.3333333333333 test
value: 0.5 test
我需要:
value: 0 test
value: 0.33333333 test
value: 0.5 test
测试代码:
double[] ar = new double[] { 0, (double)1 / 3, (double)1 / 2 };
string s = "test";
foreach (var d in ar)
{
Console.WriteLine($"value: {d} {s}");
}
{d:
后面应该加什么?
您可以使用 Alignment Component 来达到这个目的。像这样:
Console.WriteLine($"value: {d,-17} {s}");
The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.
这就是我们使用负对齐的原因,因为您希望第一列左对齐。
我需要打印双精度数,以便为值的字符串表示分配一定数量的符号(如 8)。接下来的单词应该从每个字符串中字符串开头的相同索引开始。现在我有:
value: 0 test
value: 0.3333333333333 test
value: 0.5 test
我需要:
value: 0 test
value: 0.33333333 test
value: 0.5 test
测试代码:
double[] ar = new double[] { 0, (double)1 / 3, (double)1 / 2 };
string s = "test";
foreach (var d in ar)
{
Console.WriteLine($"value: {d} {s}");
}
{d:
后面应该加什么?
您可以使用 Alignment Component 来达到这个目的。像这样:
Console.WriteLine($"value: {d,-17} {s}");
The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.
这就是我们使用负对齐的原因,因为您希望第一列左对齐。