使用字符串插值将字符串格式化为列 [英] Formatting a string into columns using String Interpolation

查看:129
本文介绍了使用字符串插值将字符串格式化为列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打印双精度,以便为字符串表示值分配一定数量的符号(如8)。下一个字应该从每个字符串中的字符串开始处起始于相同的索引。现在我有:

I need to print doubles so that definite number of symbols (like 8) is allocated for string representation of value. Next words should start at same index from beginning of string in each string. Now I have:

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:

推荐答案

您可以使用对齐组件用于此目的。像这样:

You can use Alignment Component for this purpose. Like this:

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.

所以这就是为什么我们使用负向对齐,因为你想要第一列为左对齐

So this is why we use negative alignment because you want the first column be left-aligned.

这篇关于使用字符串插值将字符串格式化为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆