[英]Words in a rectangle c#
我試圖從星星創建矩形並放入文本,但我無法弄明白。 誰能幫我?
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();
我可以把單個單詞,它沒關系,但是,如果我將更改數組索引的數量,它不能正常工作。
感謝幫助!
多字版
// 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!*
********
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.