简体   繁体   English

c#使用控制台将字符串拆分为列

[英]c# Splitting a string into columns using console

I have to get strings out of a text file and save them to a list.我必须从文本文件中获取字符串并将它们保存到列表中。 For each line I should write down the outcomes written in columns perfectly sorted under each other.对于每一行,我应该写下在彼此完美排序的列中写下的结果。

I have to write every line given in the text file down in the console.我必须在控制台中写下文本文件中给出的每一行。

I have a string build out of multiple strings like this what represents 1 line:我有一个由多个字符串组成的字符串,这样代表 1 行:

string uitslag = vertrek.ToString() +  van.ToString()  + naar.ToString() + status.ToString() + vliegtuig.ToString();`

What my question was: how can I sort the output like this:我的问题是:如何对输出进行排序:

aaaaaa    aaaaaa     aa       aaaaa       aaaaa
aaaa      aaa        aaaa     aa          aa
a         a          a        a           a
aaaaaaa   a          aaaa     aa          aaaaaaaa`

Note: I already tried using \\t but then some lines wont be in sync with the others.注意:我已经尝试使用\\t但有些行不会与其他行同步。

Edit:编辑:

`String.Format("{0}{1}{2}{3}{4}",
      vertrek.ToString().PadRight(12, ' '),
      van.ToString().PadRight(12, ' '),
      naar.ToString().PadRight(12, ' '),
      status.ToString().PadRight(12, ' '),
      vliegtuig.ToString().PadRight(12, ' '));`

gave the following result:给出了以下结果:

result结果

You can use String.PadRight with the maximum length as a space padding to the right of each string:您可以使用最大长度的String.PadRight作为每个字符串右侧的空格填充:

String.PadRight(50, ' ');

In your case:在你的情况下:

string uitslag = String.Format("{0}{1}{2}{3}{4}",    
         vertrek.ToString().PadRight(50, ' '),  
         van.ToString().PadRight(50, ' '),  
         naar.ToString().PadRight(50, ' '), 
         status.ToString().PadRight(50, ' '),                  
         vliegtuig.ToString().PadRight(50, ' '));

Change this:改变这个:

string uitslag = vertrek.ToString() +  van.ToString()  + naar.ToString() + status.ToString() + vliegtuig.ToString();

Into something like this:变成这样:

string uitslag = String.Format ("{0,-10}{1,-10}{2,-10}{3,-10}{4,-10}", vertrek.ToString(),  van.ToString(), naar.ToString(), status.ToString(), vliegtuig.ToString());

The first number in curly brackets represents the column number, the second represents the maximum number of characters in that line (negative value for left align, positive value for right align).大括号中的第一个数字表示列号,第二个数字表示该行中的最大字符数(左对齐为负值,右对齐为正值)。 So you'll want to set that value (I used 10 as an example) to whatever your maximum column width should be.因此,您需要将该值(我以 10 为例)设置为您的最大列宽。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM