Is there a built-in function to repeat a string or char in .NET?

C#asp.netvb.net

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Returns

"abab"

And

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

Returns

"aa"

Solution 2 - C#

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

returns

> "abab"

Solution 3 - C#

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

Solution 4 - C#

new String('*', 5)

See Rosetta Code.

Solution 5 - C#

The best solution is the built in string function:

 Strings.StrDup(2, "a")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHasanGView Question on Stackoverflow
Solution 1 - C#Kirk WollView Answer on Stackoverflow
Solution 2 - C#Carter MedlinView Answer on Stackoverflow
Solution 3 - C#SchiaviniView Answer on Stackoverflow
Solution 4 - C#Eli DaganView Answer on Stackoverflow
Solution 5 - C#Chris RaisinView Answer on Stackoverflow