c# - 问题:有没有办法在 C# 中像这样格式化空白?
问题描述
有没有办法在 C# 中像这样格式化空白?
我想知道你是否可以将字符串数组解析成一个方法并让它返回一个带空格的格式化字符串,我需要一种特定的方式来完成,所以这里有一个例子:
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 行。这是另一个示例,这次有两列以上:
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.
这就是我想知道的全部,如果您知道任何可以帮助我的事情,请告诉我。谢谢你们的帮助,你们真的让我很开心。
解决方案
尝试这样的事情(我在您的数据中添加了一个额外的行以使其不方形并使调试更加明显):
public static class PaddedColumns
{
private static string[][] _stringArray = new string[][] {
new [] {"Name:", "John", "Jones."},
new [] {"Date of birth:", "Monday,", "07/11/1989."},
new [] {"Age:", "29", "Years old."},
new [] {"Eye Color:", "blue", ""},
};
public static void PadIt()
{
OutputPadded(_stringArray);
}
public static void OutputPadded(string[][] strings)
{
var columnMaxes = new int[strings[0].Length];
foreach (var row in strings)
{
for (var colNo = 0; colNo < row.Length; ++colNo)
{
if (row[colNo].Length > columnMaxes[colNo])
{
columnMaxes[colNo] = row[colNo].Length;
}
}
}
const int extraPadding = 2;
//got the maxes, now go through and use them to pad things
foreach (var row in strings)
{
for (var colNo = 0; colNo < row.Length; ++colNo)
{
Console.Write(row[colNo].PadRight(columnMaxes[colNo] + extraPadding));
}
Console.WriteLine("");
}
}
}
结果如下所示:
Name: John Jones.
Date of birth: Monday, 07/11/1989.
Age: 29 Years old.
Eye Color: blue
推荐阅读
- google-sheets - Google表格中是否有任何公式长度限制?
- angular - Angular ag-grid 将数据传递到另一个组件
- python - python中“结果太大”有什么解决方案吗?
- r - 如何在r中堆叠数据框列?
- sql - PostgreSQL - 创建触发器:函数不存在
- python - 使用带有 AVX2 或 AVX512 的 PyOpenCL 编写内核函数?
- applescript - 如何使用 AppleScript 获取今日提醒数量?
- f# - FSharpPlus:当我尝试组合两个变压器时 fsi 阻塞
- reactjs - React 良好实践 - 如何构建父子组件,包括表单以及在哪里保持状态?
- javascript - 打字稿:对象文字只能指定已知属性