2008-11-17 67 views

回答

14

这取决于你所需要的...有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(); 
    } 
+1

马克你不觉得的StringBuilder()。将(0,值,计数)是更好? – 2009-04-06 10:40:10

+0

好点;根本没有看到过载... – 2009-04-06 10:42:03

5

如果你只需要重复单个字符(如你的例子),那么这将工作:

Console.WriteLine(new string('a', 3)) 
+0

只适用于“新字符串(CHAR,COUNT)”,不适用于字符串。 – Tom 2008-11-17 15:45:27

-1

如果你需要用像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(); 
    } 
5

井.NET的所有版本重复一个字符串你总是可以做到这一点

public static string Repeat(string value, int count) 
{ 
    return new StringBuilder().Insert(0, value, count).ToString(); 
} 
相关问题