[英]What is the C# equivalent of Perl's repetition operator?
In Perl 在Perl
print "a" x 3; # aaa
In C# 在C#中
Console.WriteLine( ??? )
It depends what you need... there is new string('a',3)
for example. 这取决于你需要什么......例如有new string('a',3)
。
For working with strings; 用于处理字符串; you could just loop... not very interesting, but it'll work. 你可以循环...不是很有趣,但它会工作。
With 3.5, you could use Enumerable.Repeat("a",3)
, but this gives you a sequence of strings, not a compound string. 使用3.5,您可以使用Enumerable.Repeat("a",3)
,但这会为您提供一系列字符串,而不是复合字符串。
If you are going to use this a lot, you could use a bespoke C# 3.0 extension method: 如果您打算使用它,可以使用定制的C#3.0扩展方法:
static void Main()
{
string foo = "foo";
string bar = foo.Repeat(3);
}
// stuff this bit away in some class library somewhere...
static string Repeat(this string value, int count)
{
if (count < 0) throw new ArgumentOutOfRangeException("count");
if (string.IsNullOrEmpty(value)) return value; // GIGO
if (count == 0) return "";
StringBuilder sb = new StringBuilder(value.Length * count);
for (int i = 0; i < count; i++)
{
sb.Append(value);
}
return sb.ToString();
}
如果您只需要重复单个字符(如您的示例中所示),那么这将起作用:
Console.WriteLine(new string('a', 3))
Well in all version of .NET to repeat a string you could always do this 好吧,在所有版本的.NET中重复一个字符串,你总是可以这样做
public static string Repeat(string value, int count)
{
return new StringBuilder().Insert(0, value, count).ToString();
}
If you need to do this with strings like Tom pointed out, then an extension method will do the job nicely. 如果您需要像Tom指出的那样使用字符串,那么扩展方法可以很好地完成工作。
static class StringHelpers
{
public static string Repeat(this string Template, int Count)
{
string Combined = Template;
while (Count > 1) {
Combined += Template;
Count--;
}
return Combined;
}
}
class Program
{
static void Main(string[] args)
{
string s = "abc";
Console.WriteLine(s.Repeat(3));
Console.ReadKey();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.