Problem
I’m trying to insert a specific number of indentations before a string dependent on the depth of an item, and I’m wondering if there’s a method to return a string that has been repeated X times. Example:
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 "---------".
Asked by Abe Miessler
Solution #1
If you only want to repeat the same character, use the string constructor, which takes a char and the number of times it should be repeated new String (char c, int count).
To repeat a dash five times, for example:
string result = new String('-', 5);
Output: -----
Answered by Ahmad Mageed
Solution #2
You could use string if you’re using.NET 4.0. Enumerable can be concatenated with Concat. Repeat.
int N = 5; // or whatever
Console.WriteLine(string.Concat(Enumerable.Repeat(indent, N)));
Otherwise, I’d go with Adam’s recommendation.
The reason I generally wouldn’t advise using Andrey’s answer is simply that the ToArray() call introduces superfluous overhead that is avoided with the StringBuilder approach suggested by Adam. That said, it works without.NET 4.0, and it’s quick and straightforward (and won’t kill you if efficiency isn’t a priority).
Answered by Dan Tao
Solution #3
string’s most efficient solution
string result = new StringBuilder().Insert(0, "---", 5).ToString();
Answered by c0rd
Solution #4
public static class StringExtensions
{
public static string Repeat(this string input, int count)
{
if (input.IsNullOrEmpty() || count <= 1)
return input;
var builder = new StringBuilder(input.Length * count);
for(var i = 0; i < count; i++) builder.Append(input);
return builder.ToString();
}
}
Answered by Adam Robinson
Solution #5
This is arguably the most practical method in many situations:
public static class StringExtensions
{
public static string Repeat(this string s, int n)
=> new StringBuilder(s.Length * n).Insert(0, s, n).ToString();
}
Usage is then:
text = "Hello World! ".Repeat(5);
This expands on previous responses (especially @c0rd’s). It has the following characteristics, which are not shared by all of the other strategies discussed:
Answered by Bob Sammers
Post is based on https://stackoverflow.com/questions/3754582/is-there-an-easy-way-to-return-a-string-repeated-x-number-of-times