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 "---------".
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.
Use string. Concat(Enumerable. Repeat(charToRepeat, 5)) to repeat the character "!" with specified number of times. Use StringBuilder builder = new StringBuilder(stringToRepeat.
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.
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.
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: -----
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With