簡體   English   中英

如何在 C# 中的 string.Format 中執行 Alignment?

[英]How to do Alignment within string.Format in C#?

我在 C# 中有這行代碼:

return string.Format("{0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8);

它從文本文件中提取數據,在列表框中為 output。 我想證明一半在左邊,一半在右邊,所以在夢境中:

return string.Format("align=left({0}, {1}, {2}, {3}, {4},) align=right ({5}, {6}, {7}, {8}, {9}, {10}, {11})", Name, CPSA, PostCode, Rank, Score1, Score2, Score3, Score4, Score5, Score6, Score7, Score8);

我環顧四周,但不知道該怎么做。 誰能解釋一下?

你可以這樣做:

Console.WriteLine(String.Format("{0,-10} | {1,5}", "Bill", 51));

您將在 5 個字符上向右對齊“51”。

更多示例: Align String with Spaces

有關官方參考,請參閱復合格式

此外,要將 alignment 與 C#6 字符串插值 + 格式化一起使用,為了快速參考,請按如下方式編寫:

float avg = 3.48f;
float peak = 5.00f;
$"in : {avg,5:F1} K/s | peak {peak,5:F1} K"

const int Indent = 5; // In which indent part can also refer variable
$"in : {avg,Indent:F1} K/s | peak {peak,Indent:F1} K"

將產生

"in :   3.5 K/s | peak   5.0 K"

請參閱https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM