10

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.

RBT
  • 18,275
  • 13
  • 127
  • 181
Alexander
  • 17,699
  • 19
  • 72
  • 107
  • Sorry for not properly formatting my code and thanks for the correction. – Alexander Nov 19 '12 at 15:19
  • plz, see here. http://stackoverflow.com/questions/532892/can-i-multiply-a-string-in-c/532912#532912 – Oleg Nov 19 '12 at 15:19
  • Repeating a character and repeating the string aren't the same. Voting to reopen the question. Coincidentally [the accepted answer](https://stackoverflow.com/a/3754700/465053) in the thread used to mark this question as duplicate should have been in this thread instead. – RBT Sep 02 '17 at 02:27
  • Now I found that this post is a possible duplicate of this [post](https://stackoverflow.com/q/411752/465053) instead. – RBT Sep 02 '17 at 02:39

4 Answers4

17

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.

Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
  • 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? – Alexander Nov 19 '12 at 16:50
  • For Python 3: print('.' * 10) – torina Feb 09 '17 at 11:42
3

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));
Jonathan Wood
  • 59,750
  • 65
  • 229
  • 380
3

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

Console.WriteLine(new string('.', 10));
Dan Puzey
  • 31,916
  • 3
  • 71
  • 95
-1

try something like this

string print = "";
for(int i = 0; i< 10 ; i++)
{
print = print + ".";
} 
Console.WriteLine(print);
Schuere
  • 1,519
  • 17
  • 31