2017-05-15 122 views
0

是否有一種方法來創建一個樣式爲表格(帶有列)的字符串,以便第一列中的單詞在大小限制?多行字符串的表格樣式與列和文字換行

例如:

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]); 

但是,這並不做自動換行。這個想法是一個格式化的大字符串,而不是單獨的字符串。有任何想法嗎?

+0

嘗試\ r \ n即。 http://stackoverflow.com/questions/6806841/how-can-i-create-a-carriage-return-in-my-c-sharp-string –

+0

@KevinRaffay我只想當它達到一定的字包裝大小和只在第一列。我開始相信這是不可能的。 –

+0

@DJBurb它可能的話,你必須自己做這項工作,但沒有內置任何東西。 – maccettura

回答

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

+0

看起來很有希望。讓我試試吧。 –

+0

可能有清理它的方法,但它應該給你一個好的開始。 – maccettura

+0

我看到你在做什麼,但我試圖把整個表格看作一個字符串,而不是單獨的字符串。 *仍然在玩你的答案,雖然* –

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()); 
} 
相關問題