c# - 使用 ASCII 字符绘制 2 个相邻的矩形

标签 c# drawing ascii

我的目标是绘制两个彼此相邻的矩形。我编写了绘制矩形的代码,但无法绘制两个相邻的矩形。我知道问题出在哪里,但我不知道如何解决它。非常感谢您的帮助。

class DrawRectangles
{           
    static void Main(){
        Console.WriteLine(DrawRectangle(8,8)+DrawRectangle(4,3));
    }
    static string DrawRectangle(int width,int length){
        StringBuilder sb = new StringBuilder();
        string first = "+" + " -".StringMultiplier(width-1)+ " + ";
        sb.AppendLine(first);
        for(int i=0; i<length-1;i++)
            sb.AppendLine("|"+" ".StringMultiplier(2*width-1)+"|");
        sb.Append(first);
        return sb.ToString();
    }
}   

internal static class StringExtensions
{       
    public static string StringMultiplier(this string value,int count){
        StringBuilder sb = new StringBuilder(count);
        for(int i=0;i<count;i++)
            sb.Append(value);
        return sb.ToString();
    }       
}

预期输出:

+ - - - - - - - + 
|               |
|               |
|               |
|               |+ - - - +
|               ||       |
|               ||       |
|               ||       |
+ - - - - - - - ++ - - - + 

当前输出:

+ - - - - - - - + 
|               |
|               |
|               |
|               |
|               |
|               |
|               |
+ - - - - - - - ++ - - - + 
|       |
|       |
+ - - - +

最佳答案

首先,StringMultiplier 扩展是不必要的,因为您可以使用 System.String(Char, Int32)完成同样的事情。

这是您实际需要的代码:

// Assume the Tuples are <height, width>
string DrawRectangles(params Tuple<int, int>[] measurements)
{
    var sb = new StringBuilder();
    var maxHeight = measurements.Max(measurement => measurement.Item1);

    for (var h = maxHeight; h > 0; h--)
    {
        foreach (var measurement in measurements)
        {
            // If you're on the top or bottom row of a rectangle...
            if (h == 0 || measurement.Item1 == h)
            {
                sb.Append(String.Format("{0}{1}{0}", "+", new String('-', measurement.Item2 - 2)));
                continue;
            }

            // If you're in the middle of a rectangle...
            if (measurement.Item1 > h)
            {
                sb.Append(String.Format("{0}{1}{0}", "+", new String(' ', measurement.Item2 - 2)));
                continue;
            }

            sb.Append(new String(' ', measurement.Item2));
        }

        sb.Append(Environment.NewLine);
    }

    return sb.ToString();
}

用法:

var output = DrawRectangles(new Tuple(8, 8), new Tuple(4, 3), etc...);

关于c# - 使用 ASCII 字符绘制 2 个相邻的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14392776/

相关文章:

c# - 从回收站恢复(C#)

c# - 具有相同 ViewModel 的多个实例的 MVVM-Light Messenger

C# 允许用户通过鼠标/屏幕点击在 winform 上绘图

visual-studio - 设计时在 Visual Studio .net 中画一条线

python - 当 AJAX 在 Django 中保存(并重新填充)我的表单时,为什么我会收到 '

sql-server - SQL Server 在阿拉伯语_CI_AS 排序规则中 'ی' 和 'ي' 之间没有区别

c# - 确定文本文件编码架构

c# - 如果做两件事,是否可以将 foreach 操作转换为 LINQ?

c# - 如何防止'字符被输入到文本框中?

macos - 使用核心动画层创建可动画化的半透明叠加层