How to print the same character many times with Console.WriteLine() [duplicate]
Asked Answered
H

4

13

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.

Haas answered 19/11, 2012 at 15:16 Comment(4)
Sorry for not properly formatting my code and thanks for the correction.Haas
plz, see here. https://mcmap.net/q/55690/-can-i-quot-multiply-quot-a-string-in-c/…Brosy
Repeating a character and repeating the string aren't the same. Voting to reopen the question. Coincidentally the accepted answer in the thread used to mark this question as duplicate should have been in this thread instead.Criticize
Now I found that this post is a possible duplicate of this post instead.Criticize
V
24

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.

Villous answered 19/11, 2012 at 15:19 Comment(2)
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?Haas
For Python 3: print('.' * 10)Occidental
D
4

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));
Domitiladomonic answered 19/11, 2012 at 15:19 Comment(0)
T
4

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

Console.WriteLine(new string('.', 10));
Testes answered 19/11, 2012 at 15:22 Comment(0)
E
-1

try something like this

string print = "";
for(int i = 0; i< 10 ; i++)
{
print = print + ".";
} 
Console.WriteLine(print);
Ectoplasm answered 19/11, 2012 at 15:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.