我正在尝试从星星创建矩形并放入文本中,但我无法弄明白。谁能帮我?
string s = Console.ReadLine();
string[] n = s.Split(' ');
int longest = 0;
for (int i = 0; i < n.Length; i++)
{
if(n[i].Length > longest)
{
longest = n[i].Length;
}
}
for (int i = 1; i <= n.Length + 2; i++)
{
for (int j = 1; j <= longest + 2; j++)
{
if (i == 1 || i == n.Length + 2 || j == 1 || j == longest + 2)
{
Console.Write("*");
}
if (i == 2 && j == 1)
{
Console.Write(n[0]);
}
else
Console.Write("");
}
Console.WriteLine();
}
Console.ReadLine();
我可以放一个单词而且很好但是,如果我要更改数组索引的数量,它就无法正常工作。
感谢您的帮助!
答案 0 :(得分:3)
多字版
// please, think about variables' names: what is "n", "s"?
// longest is NOT the longest word, but maxLength
string text = Console.ReadLine();
// be nice: allow double spaces, take tabulation into account
string[] words = text.Split(new char[] { ' ', '\t' },
StringSplitOptions.RemoveEmptyEntries);
// Linq is often terse and readable
int maxLength = words.Max(word => word.Length);
// try keep it simple (try avoiding complex coding)
// In fact, we have to create (and debug) top
string top = new string('*', maxLength + 2);
// ... and body:
// for each word in words we should
// - ensure it has length of maxLength - word.PadRight(maxLength)
// - add *s at both ends: "*" + ... + "*"
string body = string.Join(Environment.NewLine, words
.Select(word => "*" + word.PadRight(maxLength) + "*"));
// and, finally, join top, body and top
string result = string.Join(Environment.NewLine, top, body, top);
// final output
Console.Write(result);
对于Hello My World!
输入,输出为
********
*Hello *
*My *
*World!*
********