December 26, 2023

Repeat a String in C#

C# do not have built-in function, as of C# 12.0, to repeat a string for x number of times.

Lets say we have a string variable:

	string text = "-"; //the string we need to repeat
	int n = 5; // number-of-times to repeat

Here are some ways you can use to repeat a string value:

Using Enumerable.Repeat and string.Concat:

	string result1 = string.Concat(Enumerable.Repeat(text, n));

Using StringBuilder:

	string result2 = new StringBuilder().Insert(0, text, n).ToString();

Using Enumerable.Range, Select with string.Concat

	var repeatedStrings = Enumerable.Range(0, n).Select(i => text);
	string result3 = string.Concat(repeatedStrings);

Using String() constructor

If the required string is single character, you can also use String constructor.

	string result4 = new String('-', n);

No comments:

Post a Comment