Godfrey Owidi
Godfrey Owidi

Reputation: 11

How do I center a string of characters in lines, like how "Align Center" works in text docs in c#?

I need to generate something like this:

 *
***
 *

or

  *
 ***
*****
 ***
  *

Using this approach (because it easier for me to understand) I am able to generate the astericks in that order but not in that alignment (please not the diamond shape).

I have tried string.Format() but no center alignment just LEFT and RIGHT var asterickString = new List();

if (n % 2 == 0 || n < 1) 
    return null;

for (var i = 1; i <= n; ++i)
{
    if (i % 2 != 0)
    {
       var s = new string('*', i);
       asterickString.Add(s + "\n");
    }
}
   
for (var j = n - 1; j >= 1; --j)
{
    if (j % 2 != 0)
    {
       var k = new string('*', j);
       asterickString.Add(k + "\n");
    }
}

return string.Join("", asterickString);

Could someone give me some tips??

Upvotes: 0

Views: 604

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Well, having screen width being screenWidth you can print aligned string like this:

private static void PrintLineLeft(string value, int screenWidth) {
  Console.WriteLine(value);
}

private static void PrintLineRight(string value, int screenWidth) {
  if (value.Length >= screenWidth)
    Console.WriteLine(value);
  else
    Console.WriteLine($"{new string(' ', screenWidth - value.Length)}{value}");
}

private static void PrintLineCenter(string value, int screenWidth) {
  if (value.Length >= screenWidth)
    Console.WriteLine(value);
  else
    Console.WriteLine($"{new string(' ', (screenWidth - value.Length) / 2)}{value}");
}

Then you can put

int n = 5;

for (var i = 1; i <= n; i += 2)
  PrintLineCenter(new string('*', i), n);

for (var i = n - 2; i >= 1; i -= 2)
  PrintLineCenter(new string('*', i), n);

Fiddle

Upvotes: 1

Related Questions