2013-03-16 57 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());