问题:有没有办法在C#中格式化这样的空格? [英] Question: Is There A Way To Format White-space Like This In C#?
问题描述
是否可以在C#中格式化这样的空格?
我想知道是否可以将字符串数组解析为一种方法,并使其返回带有空格的格式化字符串,所以我有一种特定的方式需要这样做,因此下面是一个示例:
I would like to know if you could parse string arrays into a method and get it to return you a formatted string with white-spaces, there is a specific way i need this done so here's an example:
string[][] StringArray = new string[][] {
new string[] {"Name:", "John Jones."}
new string[] {"Date of birth:", "07/11/1989."}
new string[] {"Age:", "29 Years old."}
};
FormatWhiteSpace(StringArray, Padding: 5);
输出为:
Name: John Jones.
Date of birth: 07/11/1989.
Age: 29 Years old.
如您在上面的输出中所见,所有内容都已对齐,并有5个空格用于填充,这是我们在调用该方法时定义的.这正是我们想要的.我们还有一个二维数组,因为它允许我们一次解析多于1行. 这是另一个示例,这次有两个以上的列:
As you see above in the output everything is lined up and with 5 spaces for padding as defined when we called the method. This is exactly what we want. Also we have a 2 dimensional array because that allows us to parse in more than 1 line at once. Here's another example, this time with more than two columns:
string[][] StringArray = new string[][] {
new string[] {"Name:", "John", "Jones."}
new string[] {"Date of birth:", "Monday,", "07/11/1989."}
new string[] {"Age:", "29", "Years old."}
};
FormatWhiteSpace(StringArray, Padding: 2);
第二个输出将是:
Name: John Jones.
Date of birth: Monday, 07/11/1989.
Age: 29 Years old.
这就是我想知道的一切,如果您知道有什么可以帮助您的 我,请让我知道.谢谢您的帮助,你们真的让我 一天.
That's all i would like to know if you know of anything that can help me please let me know. Thanks for your help, you guys really made my day.
推荐答案
我个人喜欢使用Linq,它也适用于任意数量的列,并将计算每列所需的距离.
I personally love using Linq, also this works with any number of columns and will calculate the distance needed for each column.
void Main()
{
string[][] StringArray = new string[][] {
new [] {"Name:", "John", "Jones."},
new [] {"Date of birth:", "Monday,", "07/11/1989."},
new [] {"Age:", "29", "Years old."}};
var lines = FormatWhiteSpace(StringArray, Padding: 2);
foreach (var line in lines)
{
Console.WriteLine(line);
}
}
private IEnumerable<string> FormatWhiteSpace(string[][] StringArray, int Padding)
{
var maxLengthDict = StringArray
.Select(sa => sa.Select((s, i) => new { Column = i, MaxLength = s.Length }))
.SelectMany(x => x)
.GroupBy(x => x.Column)
.Select(x => new {Column = x.Key, MaxLength = x.Max(y => y.MaxLength)})
.ToDictionary(x => x.Column, x => x.MaxLength);
return StringArray
.Select(sa => string.Concat(sa.Select((s, i) => s.PadRight(maxLengthDict[i] + Padding))));
}
这篇关于问题:有没有办法在C#中格式化这样的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!