2017-05-15 6 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]); 

しかし、それはワードラップを行いません。考え方は、これがフォーマットされた1つの大きな文字列であり、別々の文字列ではありません。何か案は?

+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

私はあなたが何をしているのかを見ていますが、私はテーブル全体を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()); 
} 
関連する問題