具有列和自动换行的表格样式的多行字符串

时间:2017-05-15 19:38:51

标签: c# string

有没有办法创建一个样式为表(带列)的字符串,这样第一列中的单词就会包含大小限制?

例如:

 Test item that has a         $200     $300      
 long name

 Test short name              $100     $400

 Another test item            $400     $200

 Another loooooong            $600     $700
 name

我目前正在尝试这样做:

String.Format("{0,-50}\t{1}\t{2}\t{3}\n", name, prices[0], prices[1], prices[2]);

但是,这并不是自动换行。这个想法是为了一个格式化的大字符串,而不是单独的字符串。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我有一刻,所以我一起快速回答。它应该足以让你前进。

//Define how big you want that column to be (i.e the breakpoint for the string)
private const int THRESHOLD = 15;

//Formatter for your "row"
private const string FORMAT = "{0} {1} {2}\n";

public static string GetRowFormat(string name, decimal price1, decimal price2)
{
    StringBuilder sb = new StringBuilder();
    if(name.Length > THRESHOLD) //If your name is larger than the threshold
    {   
        //Determine how many passes or chunks this string is broken into                    
        int chunks = (int)Math.Ceiling((double)name.Length / THRESHOLD);

        //Pad out the string with spaces so our substrings dont bomb out
        name = name.PadRight(THRESHOLD * chunks);

        //go through each chunk
        for(int i = 0; i < chunks; i++)
        {   
            if(i == 0) //First iteration gets the prices too
            {
                sb.AppendFormat(FORMAT, name.Substring(i * THRESHOLD, THRESHOLD), price1.ToString("C").PadRight(8), price2.ToString("C").PadRight(8));
            }
            else //subsequent iterations get continuations of the name
            {
                sb.AppendLine(name.Substring(i * THRESHOLD, THRESHOLD));
            }
        }           
    }
    else //If its not larger than the threshold then just add the string
    {
        sb.AppendFormat(FORMAT, name.PadRight(THRESHOLD), price1.ToString("C").PadRight(8), price2.ToString("C").PadRight(8));
    }
    return sb.ToString();
}

我创建了一个小提琴here

答案 1 :(得分:0)

//using (var writer = new StringWriter())
using (var writer = new StreamWriter("test.txt"))
{
    var regex = new Regex("(?<=\\G.{20})");

    foreach (var item in list)
    {
        var splitted = regex.Split(item.Name);

        writer.WriteLine("{0,-20}\t{1}\t{2}", splitted[0], item.Price1, item.Price2);

        for (int i = 1; i < splitted.Length; i++)
            writer.WriteLine(splitted[i]);
    }
    //Console.WriteLine(writer.ToString());
}