首页 > 解决方案 > 打印带有字符的字符串,周围添加了很多空格

问题描述

好吧,我在复习 C# 并尝试制作一个简单的打印机。例如,您键入一个单词或短语并在其周围打印 = 符号。但是,调试它,我注意到当我超过字符限制时,它会破坏样式。例如,当我输入我的名字时,Gustavo 效果很好:

==========         ==========
========== Gustavo ==========
==========         ==========

但是当我输入我的全名时,它会在名称前添加很多空格:

==========                 ==========
==========      Gustavo Marques ==========
==========                 ==========

我想要一个建议,以便我可以使上下行的字符限制可变,或者只是找出程序在输入 O_o 之前打印额外空格的原因。按照我下面的代码:

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {

            coolConsolePrint cool = new coolConsolePrint();
            Console.WriteLine("Write down what do you like to print:");
            string thingToWrite = Console.ReadLine();
            Console.Clear();
            Console.WriteLine(cool.printWord(thingToWrite));
            Console.ReadLine();
        }
    }

    public class coolConsolePrint
    {
        public string printWord(String word)
        {
            int reps = 0;
            int sets = 0;
            string toPrintString = "";
            int wordSize = word.Length;
            char blank = ' ';
            string style = "==========";
            int styleSize = style.Length;

            while (sets < 3)
            {
                if (reps == 2)
                    toPrintString += style.PadRight(wordSize, blank) + " " + word + " ";
                else
                {
                    if (reps % 2 != 0)
                    {
                        toPrintString += style + "\n".PadLeft(styleSize + wordSize + 2, blank);
                        sets++;
                    }

                    else
                    {
                        toPrintString += style.PadRight(styleSize + wordSize + 2, blank);
                    }

                }

                reps++;

            }

            return toPrintString;
        }
        
    }
}

标签: c#console

解决方案


您必须根据单词的长度调整输出的宽度。这应该可以解决问题。

public string printWord(String word) {

  string style = "==========";
  int style_size = style.Length;
  int content_size = word.Length;
  int padding_size = 2; // makes sure that content does not sit right against style
  int line_size = content_size + (style_size * 2) + (padding_size * 2);

  string enclosing_line = 
    style.PadRight(line_size,'=') 
    + Environment.NewLine;

  string content_line = 
    style.PadRight(style_size + padding_size) 
    + word 
    + style.PadLeft((style_size + padding_size)
    + Environment.NewLine;

  return enclosing_line + content_line  + enclosing_line ;

}

编辑以修复语法错误


推荐阅读