C# 使用 Enumerable.Repeat() 的空心矩形

C# Hollow rectangle using Enumerable.Repeat()

我的任务是使用 Enumerable.Repeat 而不是嵌套循环来创建一个空心矩形。我已经这样做了。

string str;
int rows = 5;
int cols = 15;

for (int i = 1; i <= rows; i++)
{
    if (i == 1 || i == rows)
    {
        str = string.Concat(Enumerable.Repeat("*", cols));
        Console.WriteLine(str);
    }
    else
    {
        str = string.Concat(Enumerable.Repeat(" ", cols - 2));
        str = string.Concat("*", str, "*");
        Console.WriteLine(str);
    }

它工作得很好,但是我设计的空心部分看起来不像THE WAY去如果你明白我的意思......那会是什么最有效的方式去?不包括使用 StringBuilder。

在这种情况下,有一个字符串构造函数是更好的选择。这里只是从原来的一个片段来演示:

if (i == 1 || i == rows)
{
    str = string.Concat(new string('*', cols));
    Console.WriteLine(str);
}

此外,您可以通过将顶行和底行放在循环之外来简化整个过程:

int rows = 5;
int cols = 15;

 Console.WriteLine(new string('*', cols);
 foreach(string line in Enumerable.Repeat("*".Concat(new string(' ', cols-2)).Concat("*"), rows-2))
 {
      Console.WriteLine(line);
 }
 Console.WriteLine(new string('*', cols);

您可以缓存行和 Join 它们:

 string top = new string('*', cols);
 string body = "*" + new string(' ', cols - 2) + "*";

 string result = string.Join(Environment.NewLine,
   top, 
   string.Join(Environment.NewLine, Enumerable
     .Repeat(body, rows - 2)),
   top);

 Consol.Write(result);