C# 如何使用 Console.WriteLine() 多次打印相同的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13456665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:38:15  来源:igfitidea点击:

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

c#printingconsole.writeline

提问by Alexander

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

可能的重复:
是否有一种简单的方法可以返回重复 X 次的字符串?

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

如果我想在 Python 中显示一个点 10 次,我可以使用这个:

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

or this

或这个

print "." * 10

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

如何在 C# 中使用第二种方法?我尝试了以下变体:

Console.WriteLine("."*10);

but none of them worked. Thanks.

但他们都没有工作。谢谢。

采纳答案by Tim Schmelter

You can use the stringconstructor:

您可以使用string构造函数

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.

将 String 类的新实例初始化为重复指定次数的指定 Unicode 字符所指示的值。

回答by Jonathan Wood

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

我会说最直接的答案是使用for循环。这使用较少的存储。

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));

回答by Schuere

try something like this

尝试这样的事情

string print = "";
for(int i = 0; i< 10 ; i++)
{
print = print + ".";
} 
Console.WriteLine(print);

回答by Dan Puzey

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

您可以使用“字符串”构造函数之一,如下所示:

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