Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to return a string repeated X number of times?

Tags:

c#

.net

I'm trying to insert a certain number of indentations before a string based on an items depth and I'm wondering if there is a way to return a string 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 "---------". 
like image 327
Abe Miessler Avatar asked Sep 20 '10 19:09

Abe Miessler


People also ask

How do I return a string multiple times?

repeat() method: The repeat() method constructs and returns a new string which contains the specified number of copies of the string on which it was called, concatenated together.

How do I print a string multiple times in C#?

Use string. Concat(Enumerable. Repeat(charToRepeat, 5)) to repeat the character "!" with specified number of times. Use StringBuilder builder = new StringBuilder(stringToRepeat.

How do you repeat a string in JavaScript?

JavaScript String repeat() The repeat() method returns a string with a number of copies of a string. The repeat() method returns a new string. The repeat() method does not change the original string.

How do you repeat a string and time in python?

In Python, we utilize the asterisk operator to repeat a string. This operator is indicated by a “*” sign. This operator iterates the string n (number) of times. The “n” is an integer value.


1 Answers

If you only intend to repeat the same character you can use the string constructor that accepts a char and the number of times to repeat it new String(char c, int count).

For example, to repeat a dash five times:

string result = new String('-', 5); Output: ----- 
like image 189
Ahmad Mageed Avatar answered Sep 17 '22 21:09

Ahmad Mageed