使用字符串插值,如何填充给定字符?
Using string interpolation, how to pad with a given character?
我知道我在这里有危险,但在 SO/Google 中找不到:
如何使用字符串插值填充给定字符?例如:
foreach (var p in people) {
Console.WriteLine($"{p.Name,-10}: {p.Age}");
}
将导致(例如):
Joe : 26
Dan : 52
如何更改带点的空格,通过字符串插值?获得:
Joe.......: 26
Dan.......: 52
(我知道我可以做到 p.Name.PadRight(10,'.')
,但我很确定有一种方法可以使用字符串插值参数,例如填充长度)。
浏览 Microsoft's Docs for the alignment component 字符串格式,我发现了这个小摘录。
If padding is necessary, white space is used.
如果您要使用字符串插值,就会遇到空格问题。正如您之前提到的,string.PadRight()
足以作为解决方法。
@Tar 你为什么不试试这个:
var paddingWithChar = new string ('.', lengthOfPaddingAsInt);
Console.WriteLine ($"{p.Name}{paddingWithChar}:{p.Age,10}");
我知道我在这里有危险,但在 SO/Google 中找不到:
如何使用字符串插值填充给定字符?例如:
foreach (var p in people) {
Console.WriteLine($"{p.Name,-10}: {p.Age}");
}
将导致(例如):
Joe : 26
Dan : 52
如何更改带点的空格,通过字符串插值?获得:
Joe.......: 26
Dan.......: 52
(我知道我可以做到 p.Name.PadRight(10,'.')
,但我很确定有一种方法可以使用字符串插值参数,例如填充长度)。
浏览 Microsoft's Docs for the alignment component 字符串格式,我发现了这个小摘录。
If padding is necessary, white space is used.
如果您要使用字符串插值,就会遇到空格问题。正如您之前提到的,string.PadRight()
足以作为解决方法。
@Tar 你为什么不试试这个:
var paddingWithChar = new string ('.', lengthOfPaddingAsInt);
Console.WriteLine ($"{p.Name}{paddingWithChar}:{p.Age,10}");