2014-10-08 30 views
0

這可能看起來像一個微不足道的問題,但我發誓我已經用盡了所有可以找到的方法。我試圖將字典的內容輸出到文本框。這是用C#編寫的。 Idk有多相關,但我輸出到WPF文本框。我嘗試以下方法:String.Format不會創建正確的間距,用盡每種方法

Dictionary<string, int> nGramDictionary = StatisticalBreakDown.getNGramFrequency(filePath, 3); 
MasterStatsTextBlock.Text += "~N-Gram Frequency~" + "\r\n"; 
foreach (var kvp in nGramDictionary) 
{ 
    MasterStatsTextBlock.Text += string.Format("{0,-40}{1}{2}", kvp.Key, kvp.Value, Environment.NewLine); 
} 
MasterStatsTextBlock.Text += "\r\n"; 

Dictionary<string, int> nGramDictionary = StatisticalBreakDown.getNGramFrequency(filePath, 3); 
MasterStatsTextBlock.Text += "~N-Gram Frequency~" + "\r\n"; 
foreach (var kvp in nGramDictionary) 
{ 
    MasterStatsTextBlock.Text += string.Format("{0}{1}{2}", kvp.Key.PadRight(-40), kvp.Value, Environment.NewLine); 
} 
MasterStatsTextBlock.Text += "\r\n"; 

Dictionary<string, int> nGramDictionary = StatisticalBreakDown.getNGramFrequency(filePath, 3); 
MasterStatsTextBlock.Text += "~N-Gram Frequency~" + "\r\n"; 
foreach (var kvp in nGramDictionary) 
{ 
    MasterStatsTextBlock.Text += string.Format("{0}\t\t\t{1}{2}", kvp.Key, kvp.Value, Environment.NewLine); 
} 
MasterStatsTextBlock.Text += "\r\n"; 

但無論工作。每個人都發誓這些都會起作用,但他們不會。這裏是我的輸出與所有三個這些:

~N-Gram Frequency~ 
talan kirk book      1 
kirk book of       1 
book of mormon      1 
of mormon am       1 
mormon am tt       1 
am tt extraction      1 
tt extraction nephi      1 
extraction nephi nephi    1 
nephi nephi the      1 
nephi the lord      1 
the lord speaks      1 
lord speaks to      1 
speaks to his       1 
to his children      1 
his children the      1 
children the savior     1 
the savior teaches      1 
savior teaches plainly    1 
teaches plainly because    1 

請幫助。我對此感到不知所措,爲什麼這些都不行。

+4

您是否將字體設置爲非比例字體?當角色擁有不同的尺寸時,我會很驚訝地發現任何工作。我還會質疑文本框是否是顯示這些數據的最合適的方式。 – 2014-10-08 18:45:11

+0

出於好奇,「Key」值中是否有空白字符?如果在寫入條目時將'kvp.Key'替換爲'kvp.Key.Trim()',結果會不同嗎? – 2014-10-08 18:46:19

+1

使用此'string.Format(「<{0,-40}><{1}> {2}」'並檢查(或張貼)輸出。 – ths 2014-10-08 18:57:00

回答

1

我懷疑問題是你使用的是TextBox,我的猜測是你沒有將文本設置爲等寬字體......但是你試圖使用字符串格式來準確地定位值。

要調查字符串格式,我建議使用控制檯應用程序。例如,下面的演示顯示字符串格式正常工作。無論是鍵和值的最大長度,與正在爲左對齊鍵和值是右對齊:

using System; 
using System.Collections.Generic; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var data = new Dictionary<string, int> 
     { 
      { "first", 10 }, 
      { "second", 1 }, 
      { "third", 100000 } 
     }; 

     foreach (var entry in data) 
     { 
      Console.WriteLine("{0,-20}{1,8}", entry.Key, entry.Value); 
     } 
    } 
} 

嘗試在你的WPF UI,你可能會看到相同的破碎 - 除非您將字體設置爲等寬字體。

但是,等寬字體可能看起來很醜陋......在這種情況下,您可能完全不希望使用TextBox。還有其他更高級的基於文本的控件可以使用 - 或者您可以使用更適合顯示數據列表/網格的控件。