2013-03-16 14 views
1

我有一個很長的字符串,我想顯示給控制檯,並希望將字符串分成幾行,以便它沿着分詞符合良好的包裝並適合控制檯寬度。如何格式化C#字符串以適應特定的列寬度?

例子:

try 
    { 
     ... 
    } 
    catch (Exception e) 
    { 
     // I'd like the output to wrap at Console.BufferWidth 
     Console.WriteLine(e.Message); 
    } 

什麼是實現這一目標的最佳途徑?

+0

參見[System.Console(http://msdn.microsoft.com/en-us/library/system.console.aspx)班有verious方法,可以幫助你在實現它 – 2013-03-16 05:00:54

+0

@KrishnaswamySubramanian我經歷了System.Console文檔,並沒有看到任何方法來處理這個問題中陳述的情況。如果確實有一個,你會不會指出你想要的那個? Console.WriteLine方法有很多變體,但我沒有看到任何處理單詞換行的情況。 – Unome 2015-06-08 15:22:13

回答

4

布賴恩·雷諾茲已發佈一個極好的輔助方法here(經由WayBackMachine)。

要使用:

try 
    { 
     ... 
    } 
    catch (Exception e) 
    { 
     foreach(String s in StringExtension.Wrap(e.Message, Console.Out.BufferWidth)) 
     { 
      Console.WriteLine(s); 
     } 
    } 

的增強,使用新的C#擴展方法的語法:

編輯布萊恩的代碼,這樣,而不是:

public class StringExtension 
{ 
    public static List<String> Wrap(string text, int maxLength) 
    ... 

它讀取:

public static class StringExtension 
{ 
    public static List<String> Wrap(this string text, int maxLength) 
    ... 

然後使用這樣的:

foreach(String s in e.Message.Wrap(Console.Out.BufferWidth)) 
    { 
     Console.WriteLine(s); 
    } 
+0

不錯的代碼,希望它沒有使用亞麻布張貼... – EricRRichards 2015-05-30 20:01:48

+1

神奇的解決方案,擴展是簡單,優雅,並像魅力一樣工作。 +1 – Unome 2015-06-08 15:17:58

+1

這遭受鏈接腐爛,現在找不到有用的實際代碼。 :-( – 2017-03-22 21:07:45

1

嘗試此

int columnWidth= 8; 
    string sentence = "How can I format a C# string to wrap to fit a particular column width?"; 
    string[] words = sentence.Split(' '); 

StringBuilder newSentence = new StringBuilder(); 


string line = ""; 
foreach (string word in words) 
{ 
    if ((line + word).Length > columnWidth) 
    { 
     newSentence.AppendLine(line); 
     line = ""; 
    } 

    line += string.Format("{0} ", word); 
} 

if (line.Length > 0) 
    newSentence.AppendLine(line); 

Console.WriteLine(newSentence.ToString());