c# - 打印带有字符的字符串,周围添加了很多空格
问题描述
好吧,我在复习 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;
}
}
}
解决方案
您必须根据单词的长度调整输出的宽度。这应该可以解决问题。
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 ;
}
编辑以修复语法错误
推荐阅读
- java - 覆盖 DateTimeFormatter 本地化的世纪日期样式解析策略
- keycloak - 通过代理或直接从单页应用程序访问 Keycloak Admin API?
- css - 如何从输入中清除边距(引导程序)?
- python - 如何在命令行中自动运行输入/输出
- python - 我可以让一个函数在一个列表中返回多个值吗?
- python - 从python中的字符串中间删除逗号
- ios - Swift UIView 的 sizeToFit() 总是返回 0 的高度
- git - 通过使用最终内容覆盖冲突文件来手动解决 git 冲突
- javascript - 在 bootstrap col 下打开新的 div
- asp.net - 我应该如何识别微服务之间的共享域事件(事件溯源)合同?