49
votes

Is there a function in C# that returns x times of a given char or string? Or must I code it myself?

5
this is not an exact duplicate: this is a way to do it. Dim line As String = New [String]("-"c, 100)KevinDeus
Well, better late than never. I voted for re-opening this as it is not a duplicate of linked possible duplicate. Best way to repeat a character in C# does not cover repeating strings but only characters!Nope
possible duplicate of Can I "multiply" a string (in C#)?Deanna

5 Answers

60
votes
string.Join("", Enumerable.Repeat("ab", 2));

Returns

"abab"

And

string.Join("", Enumerable.Repeat('a', 2))

Returns

"aa"
58
votes
string.Concat(Enumerable.Repeat("ab", 2));

returns

"abab"

30
votes

For strings you should indeed use Kirk's solution:

string.Join("", Enumerable.Repeat("ab", 2));

However for chars you might as well use the built-in (more efficient) string constructor:

new string('a', 2); // returns aa
3
votes
new String('*', 5)

See Rosetta Code.

2
votes

The best solution is the built in string function:

 Strings.StrDup(2, "a")