Building a string of repeated characters in C#
As many different techniques as I could think of for making a string of repeated characters in C#.
char ch = 'A';
int count = 100;
// clean and concise, using the string contructor overload
var spaces1 = new string(ch, count);
// using Enumerable.Repeat to build a list of spaces,
// then folding them into a string
var spaces2 = Enumerable.Repeat(ch, count).Aggregate("", (s,c) => s+c);
// brute force of looping into a StringBuilder
var sb = new StringBuilder(count);
for (int i = 0; i < count; i++) { sb.Append(ch); }
var spaces3 = sb.ToString();
// building an array of strings, then joining without a delimiter
var spacesArray = Enumerable.Repeat(ch.ToString(), count).ToArray();
var spaces4 = string.Join(string.Empty, spacesArray);
// dirty hack with StringBuilder.Insert
var spaces5 = new StringBuilder().Insert(0, ch.ToString(), count).ToString();
// succinct hack with String.PadRight
var spaces6 = string.Empty.PadRight(count, ch);
// using ArrayList.Repeat to build the array of repeated strings
// then smushing with String.Concat
var arrayList = ArrayList.Repeat(ch, count).ToArray();
var spaces7 = string.Concat(arrayList);
Saturday, 13 February 2010
blog comments powered by Disqus