How to print the same character many times with Console.WriteLine()

28,072

Solution 1

You can use the string constructor:

Console.WriteLine(new string('.', 10));

Initializes a new instance of the String class to the value indicated by a specified Unicode character repeated a specified number of times.

Solution 2

I would say the most straight forward answer is to use a for loop. This uses less storage.

for (int i = 0; i < 10; i++)
    Console.Write('.');
Console.WriteLine();

But you can also allocate a string that contains the repeated characters. This involves less typing and is almost certainly faster.

Console.WriteLine(new String('.', 10));

Solution 3

You can use one of the 'string' constructors, like so:

Console.WriteLine(new string('.', 10));
Share:
28,072
Alexander Popov
Author by

Alexander Popov

Updated on September 02, 2020

Comments

  • Alexander Popov
    Alexander Popov almost 4 years

    Possible Duplicate:
    Is there an easy way to return a string repeated X number of times?

    If I want to display a dot 10 times in Python, I could either use this:

    print ".........."
    

    or this

    print "." * 10
    

    How do I use the second method in C#? I tried variations of:

    Console.WriteLine("."*10);
    

    but none of them worked. Thanks.

  • Alexander Popov
    Alexander Popov over 11 years
    Thanks for the answer, it worked. And just a quick general question. I am new to StackOverflow. If I see that several people have given correct answers and all of them are equally correct and exhaustive, on what basis do I mark a particular answer as best answer?
  • torina
    torina over 7 years
    For Python 3: print('.' * 10)