在C#
中生成\t
字符串的最佳方式是什么
我正在学习C#并尝试不同的方式来说同样的事情。
Tabs(uint t)
是一个返回string
t
量\t
的<{1}}的函数
例如Tabs(3)
返回"\t\t\t"
这三种实施Tabs(uint numTabs)
的方法中哪一种最好?
当然,这取决于“最佳”的含义。
LINQ版只有两行,很不错。但重复和聚合的调用是否会不必要地消耗时间/资源?
StringBuilder
版本非常清楚,但StringBuilder
类的速度有点慢吗?
string
版本是基本的,这意味着它很容易理解。
根本不重要吗?它们都是平等的吗?
这些都是帮助我更好地了解C#的问题。
private string Tabs(uint numTabs)
{
IEnumerable<string> tabs = Enumerable.Repeat("\t", (int) numTabs);
return (numTabs > 0) ? tabs.Aggregate((sum, next) => sum + next) : "";
}
private string Tabs(uint numTabs)
{
StringBuilder sb = new StringBuilder();
for (uint i = 0; i < numTabs; i++)
sb.Append("\t");
return sb.ToString();
}
private string Tabs(uint numTabs)
{
string output = "";
for (uint i = 0; i < numTabs; i++)
{
output += '\t';
}
return output;
}
答案 0 :(得分:1320)
这个怎么样:
string tabs = new String('\t', n);
n
是您想要重复字符串的次数。
或更好:
static string Tabs(int n)
{
return new String('\t', n);
}
答案 1 :(得分:121)
string.Concat(Enumerable.Repeat("ab", 2));
返回
&#34; ABAB&#34;
和
string.Concat(Enumerable.Repeat("a", 2));
返回
&#34; AA&#34;
...从
Is there a built-in function to repeat string or char in .net?
答案 2 :(得分:117)
在所有版本的.NET中,您都可以重复一个字符串:
public static string Repeat(string value, int count)
{
return new StringBuilder(value.Length * count).Insert(0, value, count).ToString();
}
要重复一个角色,new String('\t', count)
是最好的选择。请参阅the answer by @CMS。
答案 3 :(得分:60)
最好的版本肯定是使用内置方式:
string Tabs(int len) { return new string('\t', len); }
在其他解决方案中,更喜欢最简单;只有当这证明太慢时,才能寻求更有效的解决方案。
如果你使用
废话:当然上面的代码更有效。StringBuilder
并提前知道它的结果长度,那么也使用一个合适的构造函数,这样效率要高得多,因为它意味着只进行一次耗时的分配,而且没有不必要的数据复制。
答案 4 :(得分:49)
扩展方法:
public static string Repeat(this string s, int n)
{
return new String(Enumerable.Range(0, n).SelectMany(x => s).ToArray());
}
public static string Repeat(this char c, int n)
{
return new String(c, n);
}
答案 5 :(得分:40)
使用扩展方法怎么样?
public static class StringExtensions
{
public static string Repeat(this char chatToRepeat, int repeat) {
return new string(chatToRepeat,repeat);
}
public static string Repeat(this string stringToRepeat,int repeat)
{
var builder = new StringBuilder(repeat*stringToRepeat.Length);
for (int i = 0; i < repeat; i++) {
builder.Append(stringToRepeat);
}
return builder.ToString();
}
}
然后你可以写:
Debug.WriteLine('-'.Repeat(100)); // For Chars
Debug.WriteLine("Hello".Repeat(100)); // For Strings
请注意,对于简单字符而不是字符串使用stringbuilder版本的性能测试会给您一个主要的性能依据:
在我的电脑上,测量性能的差异在1:20之间:
Debug.WriteLine(' - '。重复(1000000))// char版本和
Debug.WriteLine(“ - ”。Repeat(1000000))// string version
答案 6 :(得分:22)
这个怎么样:
//Repeats a character specified number of times
public static string Repeat(char character,int numberOfIterations)
{
return "".PadLeft(numberOfIterations, character);
}
//Call the Repeat method
Console.WriteLine(Repeat('\t',40));
答案 7 :(得分:19)
我知道这个问题已经有五年了,但有一种简单的方法可以重复一个甚至可以在.Net 2.0中运行的字符串。
重复一个字符串:
string repeated = new String('+', 3).Replace("+", "Hello, ");
返回
“你好,你好,你好,”
将字符串重复为数组:
// Two line version.
string repeated = new String('+', 3).Replace("+", "Hello,");
string[] repeatedArray = repeated.Split(',');
// One line version.
string[] repeatedArray = new String('+', 3).Replace("+", "Hello,").Split(',');
返回
{“你好”,“你好”,“你好”,“”}
保持简单。
答案 8 :(得分:17)
假设您要重复'\ t'次,您可以使用;
String.Empty.PadRight(n,'\t')
答案 9 :(得分:17)
您的第一个使用Enumerable.Repeat
的示例:
private string Tabs(uint numTabs)
{
IEnumerable<string> tabs = Enumerable.Repeat(
"\t", (int) numTabs);
return (numTabs > 0) ?
tabs.Aggregate((sum, next) => sum + next) : "";
}
使用String.Concat
可以更紧凑地重写
private string Tabs(uint numTabs)
{
return String.Concat(Enumerable.Repeat("\t", (int) numTabs));
}
答案 10 :(得分:14)
使用String.Concat
和Enumerable.Repeat
会更便宜
而不是使用String.Join
public static Repeat(this String pattern, int count)
{
return String.Concat(Enumerable.Repeat(pattern, count));
}
答案 11 :(得分:8)
var str = new string(Enumerable.Repeat('\t', numTabs).ToArray());
答案 12 :(得分:4)
答案实际上取决于您想要的复杂程度。例如,我想用竖线标记所有缩进,所以我的缩进字符串确定如下:
return new string(Enumerable.Range(0, indentSize*indent).Select(
n => n%4 == 0 ? '|' : ' ').ToArray());
答案 13 :(得分:2)
您可以创建扩展方法
static class MyExtensions
{
internal static string Repeat(this char c, int n)
{
return new string(c, n);
}
}
然后你可以像这样使用它
Console.WriteLine('\t'.Repeat(10));
答案 14 :(得分:1)
还有另一种方法
new System.Text.StringBuilder().Append('\t', 100).ToString()
答案 15 :(得分:1)
对我来说很好:
public static class Utils
{
public static string LeftZerosFormatter(int zeros, int val)
{
string valstr = val.ToString();
valstr = new string('0', zeros) + valstr;
return valstr.Substring(valstr.Length - zeros, zeros);
}
}
答案 16 :(得分:1)
毫无疑问,公认的答案是重复单个字符的最佳和最快方法。
Binoj Anthony的答案是重复字符串的一种简单而有效的方法。
但是,如果您不介意更多代码,则可以使用我的数组填充技术来更快地有效创建这些字符串。在我的比较测试中,下面的代码执行时间大约是StringBuilder.Insert代码的35%。
public static string Repeat(this string value, int count)
{
var values = new char[count * value.Length];
values.Fill(value.ToCharArray());
return new string(values);
}
public static void Fill<T>(this T[] destinationArray, params T[] value)
{
if (destinationArray == null)
{
throw new ArgumentNullException("destinationArray");
}
if (value.Length > destinationArray.Length)
{
throw new ArgumentException("Length of value array must not be more than length of destination");
}
// set the initial array value
Array.Copy(value, destinationArray, value.Length);
int copyLength, nextCopyLength;
for (copyLength = value.Length; (nextCopyLength = copyLength << 1) < destinationArray.Length; copyLength = nextCopyLength)
{
Array.Copy(destinationArray, 0, destinationArray, copyLength, copyLength);
}
Array.Copy(destinationArray, 0, destinationArray, copyLength, destinationArray.Length - copyLength);
}
有关此数组填充技术的更多信息,请参见Fastest way to fill an array with a single value
答案 17 :(得分:0)
试试这个:
答案 18 :(得分:0)
用6,435 z填充屏幕 $ str = [System.Linq.Enumerable] :: Repeat([string] :: new(“ z”,143),45)
$ str
答案 19 :(得分:-1)
尽管与先前的建议非常相似,但我希望保持简单并应用以下内容:
string MyFancyString = "*";
int strLength = 50;
System.Console.WriteLine(MyFancyString.PadRight(strLength, "*");
实际上是标准.Net,