2015-09-02 72 views
0

我試圖與格式()方法 不幸的是,我得到這個結果與foreach循環來格式化字符串表的佈局:實現與的String.Format

代碼:

output += String.Format("{0,17} {1,48}\n\n", "Name", "Description "); 

Console.WriteLine(output); 

string outputloop; 

foreach (IMetricContract contract in metrics) 
{  
    outputloop = String.Format("{0,17} {1,48}\n", contract.Name, contract.Description);     
    Console.WriteLine(outputloop); 
} 

結果: enter image description here

您可以看到元素位於不同的位置,但我已經定義了相同的值。 任何人都知道解決方案?

編輯:

outputloop = String.Format("{0,-17} {1,-48}\n", contract.Name, 

我也試圖與該職位負值,但後來我得到這個

結果: enter image description here

結果應該是這個樣子(編輯帶Imageeditor)

enter image description here

+0

是否有可能採取的第一個字符要放在一個位置的字符串,似乎該方法是這樣做的無線th最後一個字符,這將解釋不正確的格式 –

+2

是的,這就是所謂的右對齊,它似乎做得完全正確。舉例說明這個_should_如何格式化。 – CodeCaster

+0

@Sayse是標題也在不同的位置,但我通過設置foreach元素從17到16處理,更大的問題是元素誰不在正確的位置 –

回答

0

因此,最後我發現如何解決這個任務,而不是格式函數,我在c#中的字符串使用padright函數。 這兩個網站給我的幫助:

http://www.dotnetperls.com/padright

https://msdn.microsoft.com/en-us/library/66f6d830(v=vs.110).aspx

這裏是我的代碼:

foreach (IMetricContract contract in metrics) 
      { 
       name = contract.Name; 
       desc = contract.Description; 

       Console.Write("".PadRight(13,'#')+name.PadRight(41,'i')); 
       Console.WriteLine(desc + "\n"); 

      } 

屏幕: enter image description here

3

如果我理解正確的,我想你想負數,如:

outputloop = String.Format("{0,-17} {1,-48}\n", contract.Name, contract.Description); 

這使得左對齊(而不是右側)。

無論您使用正數還是負數,當實際字符數超過絕對值48(在本例中)時,「額外」字符將超出「字段」的右側。

+0

我認爲你可能是對的,但我仍然對操作後的內容感到困惑,[這裏是鏈接](https://msdn.microsoft.com/en-us/library/system.string.format% 28v = vs.110%29.aspx#FormatItem)添加到解釋對齊的文檔中,我刪除了我的其他評論:) – Sayse

+0

我剛剛編輯了我的文章 –

+1

@ArturKaraev不要忘記在標題行中加入缺陷所以'String.Format(「{0,-17} {1,-48} \ n \ n」,「Name」,「Description」)'在開頭。 –