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));
![Alexander Popov](https://i.stack.imgur.com/8ddoM.jpg?s=256&g=1)
Author by
Alexander Popov
Updated on September 02, 2020Comments
-
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 over 11 yearsThanks 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 over 7 yearsFor Python 3: print('.' * 10)