我试图在基于项深度的字符串之前插入一定数量的缩进,我想知道是否有一种方法可以返回一个重复X次的字符串。例子:
string indent = "---";
Console.WriteLine(indent.Repeat(0)); //would print nothing.
Console.WriteLine(indent.Repeat(1)); //would print "---".
Console.WriteLine(indent.Repeat(2)); //would print "------".
Console.WriteLine(indent.Repeat(3)); //would print "---------".
你可以创建一个ExtensionMethod来做这件事!
public static class StringExtension
{
public static string Repeat(this string str, int count)
{
string ret = "";
for (var x = 0; x < count; x++)
{
ret += str;
}
return ret;
}
}
或者使用@丹涛解决方案:
public static class StringExtension
{
public static string Repeat(this string str, int count)
{
if (count == 0)
return "";
return string.Concat(Enumerable.Repeat(indent, N))
}
}
字符串和字符[版本1]
string.Join("", Enumerable.Repeat("text" , 2 ));
//result: texttext
字符串和字符[版本2]:
String.Concat(Enumerable.Repeat("text", 2));
//result: texttext
字符串和字符[版本3]
new StringBuilder().Insert(0, "text", 2).ToString();
//result: texttext
识字课只有:
'5' * 3;
//result: 555
识字课只有:
new string('5', 3);
//result: 555
扩展方法:
(工作更快-更好的WEB)
public static class RepeatExtensions
{
public static string Repeat(this string str, int times)
{
var a = new StringBuilder();
//Append is faster than Insert
( () => a.Append(str) ).RepeatAction(times) ;
return a.ToString();
}
public static void RepeatAction(this Action action, int count)
{
for (int i = 0; i < count; i++)
{
action();
}
}
}
用法:
var a = "Hello".Repeat(3);
//result: HelloHelloHello