如何在c#中以菱形格式打印字符串

时间:2015-11-26 07:35:24

标签: c# string for-loop

如果我有一个单词“start”,我想使用 for loop

这样打印
   a
  tar
 start
  tar
   a

当用户输入奇数长度的字符串时,如何在c#中打印字符串,例如:“START”,“QUESTIONS”

这是我的代码

string input;
for (int i = 1; i <= input.Length; i++)
{
    for (int j = 0; j < (input.Length - 2); j++)
        Console.Write(" "); 
    for (int j = number; j < (number - 1); j--)
    {
        Console.Write(input[j]);
    }
    for (int k = number; k < i && k > 0; k++)
        Console.Write(input[k]); 
    Console.WriteLine();
}

3 个答案:

答案 0 :(得分:3)

我怀疑这个 Linq 例程是否会被接受为家庭作业解决方案,但是它可能对您测试您自己的代码非常有用:

   String source = "start";

   String result = String.Join(Environment.NewLine, Enumerable
     .Range(0, source.Length)
     .Select(index => source.Length - Math.Abs(index - source.Length / 2) * 2)
     .Where(length => length > 0) // for even size words, e.g. "star"
     .Select(length => source
       .Substring((source.Length - length) / 2, length)
       .PadLeft((source.Length - length) / 2 + length, ' ')));

   // Test
   //   a
   //  tar
   // start
   //  tar
   //   a
   Console.Write(result);

答案 1 :(得分:0)

如果确实需要for-loop解决方案,则可以执行此操作

string input = "questions"; //for example
if (input.Length % 2 == 0)
    return; //as per given condition, only ODD length strings

var isReducing = false;
for (int i = 0, len = 1, startIndex = (input.Length - 1) / 2; i < input.Length; i++)
{
    var str = input.Substring(startIndex, len);
    Console.WriteLine(str.PadLeft(len + startIndex, ' '));
    if (len == input.Length)
        isReducing = true;
    startIndex = isReducing ? startIndex + 1 : startIndex - 1;
    len = isReducing ? len - 2 : len + 2;
}

答案 2 :(得分:0)

2 x for-loop如何:)

        string s = "0123456";
        int l = s.Length;
        int c = l / 2 + 1; //center

        for (int i = 0; i < c; i++)
            Console.WriteLine(s.Substring(c - i - 1, i * 2 + 1).PadLeft(c + i, ' '));
        for (int i = c - 2; i >= 0; i--)
            Console.WriteLine(s.Substring(c - i - 1, i * 2 + 1).PadLeft(c + i, ' '));