Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用字符串格式_C#_C# 4.0_C# 3.0 - Fatal编程技术网

C# 如何使用字符串格式

C# 如何使用字符串格式,c#,c#-4.0,c#-3.0,C#,C# 4.0,C# 3.0,我在下面有一个字符串数组,希望像下面这样格式化,最好的方式是什么?提前谢谢 line[0] = "This is line one two tree"; line[1] = "This is Abc Cde"; line[2] = "This is cjdj"; 我希望它的格式显示如下 This is line one two tree This is Abc Cde.......... This is cjdj............. 使用string.PadRight将每个字符串填充到

我在下面有一个字符串数组,希望像下面这样格式化,最好的方式是什么?提前谢谢

line[0] = "This is line one two tree";
line[1] = "This is Abc Cde";
line[2] = "This is cjdj";
我希望它的格式显示如下

This is line one two tree
This is Abc Cde..........
This is cjdj.............

使用
string.PadRight
将每个字符串填充到指定长度,并使用指定字符的实例。

您可以使用:

var output = string.Join(Environment.NewLine, line.Select(l => l.PadRight(line[0].Length, '-').ToArray());
在确定字符串数组中哪一个最宽时,可以使用:

var width = line.Max(l => l.Length);
foreach (var l in line)
    Console.WriteLine(l.PadRight(width, '.'));
使用PadRight:

e、 g


这很有效,也很简洁。但是,我会得到最大长度一次,否则你会为每个循环重新计算它。在你的循环之前提取出
max
,并使用它。,+1如果足够,我会更新它…为什么在回答问题时否决了它?请保留文明和建设性的评论。
int len = line[0].Length;
Console.WriteLine(line[0]);
Console.WriteLine(line[1].PadRight(len,"."));
Console.WriteLine(line[2].PadRight(len,"."));