c# - c#文本文件上的间距对齐
问题描述
根据下面的图像,我希望像图像右侧一样具有正确且一致的对齐和间距。
下面是我的第一个输出的源代码,请帮助谢谢
string line = null;
string printout = null;
StringBuilder sb = new StringBuilder(line);
if (File.Exists(filePath))
{
StreamReader file = null;
file = new StreamReader(filePath);
try
{
while ((line = file.ReadLine()) != null)
{
if (line == string.Empty)
{
continue;
}
if (!line.StartsWith("-"))
{
if ((line.Length <= 82) || line.Contains("MY01"))
{
printout = String.Format(line.Remove(0, 5).ToUpper());
var result = Regex.Replace(printout, "[\t ][ ]{10}", " ");
Console.WriteLine(result);
}
}
}
}
catch (IOException e)
{
Console.WriteLine("not valid", e.Message);
}
finally
{
if (file != null)
file.Close();
}
}
}
}
解决方案
很难确切地看到您的原始文件格式是什么样的,但这里有一种方法可以将string.PadRight
每个列项填充到该列的正确宽度。
如果我们假设我们有一个像左边那样的输入文件,这个方法会将它格式化为类似于右边那个的格式。
这可能不是最有效的方法,但它的作用是:
- 读取文件的所有行,并对于每一行,将其以空格字符拆分为“项目”数组。
- 查找每列的最大宽度并将其保存在字典中,以列索引为键,列宽为值
- 在首先将每个行项的宽度设置为该列的正确宽度后,将每一行写回文件
public static void FormatTextColumns(string filePath)
{
// Minimum number of spaces between two columns
var minColSpace = 3;
// Dictionary holds the index and max width of each column
var columnWidths = new Dictionary<int, int>();
// Read each file line into an array of items by splitting the line on whitespace
var lineItems = File
.ReadAllLines(filePath)
.Select(line => line.Split(new char[0], StringSplitOptions.RemoveEmptyEntries))
.ToList();
// Get the max column count
var maxColumns = lineItems.Max(x => x.Length);
// Save the max width of each column
for (var i = 0; i < maxColumns; i++)
{
foreach (var line in lineItems)
{
if (line.Length > i)
{
int existingValue;
columnWidths.TryGetValue(i, out existingValue);
columnWidths[i] = Math.Max(line[i].Length, existingValue);
}
}
}
// Save each line back to the file after padding each column item to the correct length
File.WriteAllLines(filePath, lineItems.Select(line =>
string.Concat(line.Select((item, index) =>
item.PadRight(columnWidths[index] + minColSpace)))));
}
样本文件输入:
CISCO ZPRPflubadub 08-0729-01-MARch 08-0729-01 1 EA
CISCO ZPRP 08-0729-01-MAR 08-0729-0134 1 EA
CISCO ZPRP 08-0729-01-MAR 08-0729-01 1 EA
CISCO ZPRP 08-0729-01-MAR 08-0729-01 10 EA 4
CISCOar ZPRP 08-0729-01-MAR 08-0729-01 1 EA
CISCO ZPRP 08-0729-01-MARffe 08-0729-01 1 EA
示例文件输出:
CISCO ZPRPflubadub 08-0729-01-MARch 08-0729-01 1 EA
CISCO ZPRP 08-0729-01-MAR 08-0729-0134 1 EA
CISCO ZPRP 08-0729-01-MAR 08-0729-01 1 EA
CISCO ZPRP 08-0729-01-MAR 08-0729-01 10 EA 4
CISCOar ZPRP 08-0729-01-MAR 08-0729-01 1 EA
CISCO ZPRP 08-0729-01-MARffe 08-0729-01 1 EA