黑马程序员技术交流社区
标题:
从控件台输出一个弓形
[打印本页]
作者:
fcyan86
时间:
2013-5-31 17:21
标题:
从控件台输出一个弓形
本帖最后由 fcyan86 于 2013-6-1 22:01 编辑
从控件台输出一个弓形,行数不定,列数不定,我代码是这样的,有没有更加简单的
#region//
//一行30个,弓形,行距两行
string tempStr = str;//不定长度的字符串,将该字符串按弓形输出
StringBuilder outStr=new StringBuilder();//最后要从控制台输出的字符串
int index = 0;//字符串索引
int row = 0;//行索引
string spaces = "";//空格
for (int j = 0; j < 30-1; j++)
{
spaces += " ";
}
bool leftToRight = true;
int rowLength = 0;
do
{
rowLength = tempStr.Length - index > 30 ? 30 : tempStr.Length - index;
if (row%3 == 0 && leftToRight)
{
//从左到右
outStr.Append(tempStr.Substring(index, rowLength));
index += 30;
leftToRight = false;
}
else if(row%3==0)
{
//从右到左
string tempRowStr = tempStr.Substring(index, rowLength);
Stack<char> stack=new Stack<char>();
for (int k = 0; k < 30;k++ )
{
if(k<tempRowStr.Length)
stack.Push(tempRowStr[k]);
else
{
stack.Push(' ');
}
}
char[] tempChars = new char[30];
for (int k = 0; k <30; k++)
{
tempChars[k] = stack.Pop();
}
outStr.Append(new string(tempChars));
index += 30;
leftToRight = true;
}
else if (leftToRight)
{
//左边从上到下
outStr.Append(tempStr.Substring(index, 1) + spaces);
index++;
}
else
{
//右边从上到下
outStr.Append(spaces + tempStr.Substring(index, 1));
index++;
}
row++;
outStr.Append("\n");
if(index>tempStr.Length)
break;
} while (true);
#endregion
复制代码
作者:
fcyan86
时间:
2013-6-1 22:02
……自已结贴………………
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2