2009-11-25 127 views
-1

我想通過確保顯示的第二個字符串出現在第一個字符串輸出的中間位置來將字符串對準另一個字符串。我該如何在C#中做這件事。在此先感謝將一個字符串與另一個字符串對齊

+1

這是控制檯輸出,WPF,還是什麼? – HackedByChinese 2009-11-25 19:22:32

+0

您是在談論ASP.NET,控制檯還是Web窗體? – 2009-11-25 19:22:37

+0

什麼......那個?是吧? – 2009-11-25 19:22:38

回答

5

你的問題有點不清楚(例子有助於澄清)。此外,你還沒有完全指定你期望的輸出(當第二個字符串不能居中在第一個字符串上,因爲它太長了嗎?)你會發現完全specifying your requirements將幫助你編寫代碼!這就是說,我認爲你正在尋找類似以下的東西。

使用

public static string CenterWithRespectTo(string s, string against) { 
    if(s == null) { 
     throw new ArgumentNullException("s"); 
    } 
    if(against == null) { 
     throw new AgrumentNullException("against"); 
    } 
    if (s.Length > against.Length) { 
     throw new InvalidOperationException(); 
    } 
    int halfSpace = (against.Length - s.Length)/2; 
    return s.PadLeft(halfSpace + s.Length).PadRight(against.Length); 
} 

使

string s = "Hello"; 
string against = "My name is Slim Shady"; 
Console.WriteLine(CenterWithRespectTo(s, against) + "!"); 
Console.WriteLine(against); 

產生

 Hello  ! 
My name is Slim Shady 

(將多餘的 '!' 是爲了讓你能看到的填充。)

你可以很容易地修改這個在存在奇數額外空間的情況下,額外空間根據您的需要左右移動(目前它在右側)(重構接受參數!)。

+0

這隻適用於非比例(固定寬度)字體。一般來說,對於所有字體......如果兩個字符串不對稱地填充了不同的寬度字符(第一個字符串具有寬字符的優先級(Ws,Ms,Hs等),並且第二個字符串具有窄字符的優勢,如i,l ,標點符號等),那麼這將不起作用。 – 2009-11-25 20:00:19

+0

他說中心字符串,而不是字符串(文本)的中心視覺表示。 (我同意這樣一個明顯的陳述,即他的要求是模糊不清的。) – jason 2009-11-25 20:43:36

0

您的問題不清楚。也許.PadLeft.PadRight方法會幫助你。

3

最簡單的解決方案是將字符串放入水平對齊的文本框中,並將它們的textalignment屬性設置爲「居中」。

否則,你需要衡量字符串的長度像素,在指定的字體繪製的時候......那麼抵銷了兩個長度之差的一半短字符串的開始x座標...

string s1 = "MyFirstString"; 
string s2 = "Another different string"; 
Font f1 = new Font("Arial", 12f); 
Font f2 = new Font("Times New Roman", 14f); 
Graphics g = CreateGraphics(); 
SizeF sizeString1 = g.MeasureString(s1, f1), 
     sizeString2 = g.MeasureString(s2, f2); 
float offset = sizeString2.Width - sizeString1.Width/2; 
// Then offset (to the Left) the position of the label 
// containing the second string by this offset value... 
// offset to the left, because If the second string is longer, 
// offset will be positive. 
Label lbl1 = // Label control for string 1, 
     lbl2 = // Label control for string 2; 
lbl1.Text = s1; 
lbl1.Font = f1; 
lbl1.Left = //Some value; 
lbl2.Text = s2; 
lbl2.Font = f2; 
lbl2.Left == lbl1.Left - offset; 
+0

這會將字符串(文本)的可視表示集中在一個窗口中,但不一定是他試圖解決的問題。 – jason 2009-11-25 20:43:06

相關問題