7
A
回答
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();
}
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();
}
相关问题
- 1. 什么是Perl的qq操作符的Java等价物?
- 2. C&C++中的'&'是什么,它在perl中的等价操作符是什么?
- 3. C#中TreeBidiMap的等价物是什么?
- 4. 什么是C#中的vbNullChar等价物?
- 5. 什么是ChrW(e.KeyCode)的C#等价物?
- 6. C#中memset的等价物是什么?
- 7. 什么是C?:operator的Ruby等价物?
- 8. C#中bigint的等价物是什么?
- 9. 什么是CRT的C++等价物?
- 10. 什么是Java Socket.getInetAddress()的C#等价物?
- 11. 什么是Java DecimalFormat的c#等价物?
- 12. 什么是UINT32_MAX的C++等价物?
- 13. 什么是MsgWaitForMultipleObjects的C#等价物?
- 14. 什么是EventWaitHandle的Objective C等价物?
- 15. 什么是C++ typeid的Scala等价物?
- 16. 什么是PHP的proc_open(),proc_close()等Perl的等价物?
- 17. 什么是R的Perl的地图和grep的等价物?
- 18. 什么是在ASP.NET中的CRON作业的等价物? - C#
- 19. 什么是Perl的DBI的Python等价物?
- 20. 什么是PHP的$ _SERVER [...]的Perl等价物?
- 21. 什么是Perl的FindBin的Python等价物?
- 22. 什么是Perl的反引号的Python等价物?
- 23. 什么是Perl的ucfirst()或s /// e的Python等价物?
- 24. 什么是Python的os.walk的等价物?
- 25. 什么是PHP的preg_quote的等价物?
- 26. MessageFormat的Pattern.quote()的等价物是什么?
- 27. 什么是PHP中$ _SERVER ['HTTP_HOST']的Perl等价物?
- 28. 这个Perl脚本的PHP等价物是什么?
- 29. Perl中bash导出的等价物是什么?
- 30. 什么是Win32_OperatingSystem的64位等价物?
马克你不觉得的StringBuilder()。将(0,值,计数)是更好? – 2009-04-06 10:40:10
好点;根本没有看到过载... – 2009-04-06 10:42:03