【发布时间】:2010-09-22 16:33:58
【问题描述】:
在 Perl 中
print "a" x 3; # aaa
在 C# 中
Console.WriteLine( ??? )
【问题讨论】:
在 Perl 中
print "a" x 3; # aaa
在 C# 中
Console.WriteLine( ??? )
【问题讨论】:
这取决于您需要什么...例如new string('a',3)。
用于处理字符串;你可以循环......不是很有趣,但它会工作。
在 3.5 中,您可以使用 Enumerable.Repeat("a",3),但这会为您提供字符串序列,而不是复合字符串。
如果您要经常使用它,可以使用定制的 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))
【讨论】:
在所有版本的 .NET 中重复一个字符串你总是可以这样做
public static string Repeat(string value, int count)
{
return new StringBuilder().Insert(0, value, count).ToString();
}
【讨论】:
如果您需要像 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();
}
【讨论】: