如何显示带有内容的星号矩形?

时间:2019-01-31 03:57:06

标签: c# c#-4.0

使用在C# Corner上找到的代码,我试图创建一个带有文本内容的星号矩形,但是它似乎不起作用。它打印文本“ Program to Print Rectangle *'s”,但不打印矩形。关于如何实现此目标的任何想法?代码如下:

using System;

public class Program
{
    public static void Main()
    {
        int height = 5;
        int width = 5;

        for (int i = 1; i <= height; i++)
        {
            for (int j = 1; j <= width; j++)
            {
                if ((i == 1 || i == height) || (j == 1 || j == width))
                {
                    Console.Write("*"); //prints at border place
                }
                else
                {
                    Console.Write(" "); //prints inside other than border
                }
            }
            Console.WriteLine();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

尝试此代码。

string myText = "Hello World";
int width = myText.Length + 2, height = 3;
for (int i = 1; i <= height; i++)
{
    for (int j = 1; j <= width; j++)
    {
        if ((i == 1 || i == height) || (j == 1 || j == width))
            Console.Write("*"); //prints at border place
        else
            Console.Write(myText[j - 2]); //prints inside other than border
    }
    Console.WriteLine();
}