2012-10-11 17 views
5

我在C#.NET4控制檯應用程序中使文本居中出現問題。C#控制檯應用程序中的文本只能用於某些輸入

這是我爲中心的文本方法:

private static void centerText(String text) 
{ 
    int winWidth = (Console.WindowWidth/2); 
    Console.WriteLine(String.Format("{0,"+winWidth+"}", text)); 
} 

不過,我剛剛得到的產出,因爲它會被正常輸出。 如果我不過使用此行:

Console.WriteLine(String.Format("{0,"+winWidth+"}", "text")); 

「文本」被中心,因爲它應該。

我打電話centerText這兩種方法:

​​
+0

當/因爲你的文字較長屏幕的寬度的一半將出現問題更換windowsWidth90。 – DaveShaw

+0

@DaveShaw還有一個比這個更大的問題:文本寬度甚至從未成爲居中的一部分。 –

回答

10

試試這個:

private static void centerText(String text) 
{ 
    Console.Write(new string(' ', (Console.WindowWidth - text.Length)/2)); 
    Console.WriteLine(text); 
} 

與您最初的代碼的問題是,你的文字開始在屏幕中央。你希望文本的中心在那裏。

如果你想打印整個段落的中心,你會做更多的工作。

+0

謝謝!奇蹟般有效! –

1

傳遞可能有空格,如\r\n文本,然後刪除該調用寫入如

string textClean = Regex.Replace(text, @"([\r\n])", string.Empty); 

// Then center on text clean 
+0

雖然這是一個很好的建議,但它似乎並不是這裏的根本問題。因此,這可能只是一個評論。 – Servy

0

我有我自己的方法調用控制檯頭前:

public static void Header(string title, string subtitle = "", ConsoleColor color = ConsoleColor.White) 
{ 
    int windowWidth = 90 - 2; 
    string titleContent = String.Format("║{0," + ((windowWidth/2) + (title.Length/2)) + "}{1," + (windowWidth - (windowWidth/2) - (title.Length/2) + 1) + "}", title, "║"); 
    string subtitleContent = String.Format("║{0," + ((windowWidth/2) + (subtitle.Length/2)) + "}{1," + (windowWidth - (windowWidth/2) - (subtitle.Length/2) + 1) + "}", subtitle, "║"); 

    Console.WriteLine("╔════════════════════════════════════════════════════════════════════════════════════════╗"); 
    Console.WriteLine(titleContent); 
    if (!string.IsNullOrEmpty(subtitle)) 
    { 
     Console.WriteLine(subtitleContent); 
    } 
    Console.WriteLine("╚════════════════════════════════════════════════════════════════════════════════════════╝"); 
} 

然後你這樣稱呼它YourStaticClass.Header("Test", "Version 1.0");

它應該看起來像這樣:

╔════════════════════════════════════════════════════════════════════════════════════════╗ 
║           Test           ║ 
║          Version 1.0          ║ 
╚════════════════════════════════════════════════════════════════════════════════════════╝ 

您可以Console.WindowWidth

相關問題