Home >Backend Development >C++ >How Can I Repeat a String Multiple Times for Indentation in C#?
Repeating Strings for Indentation
In your scenario, you need a way to repeat a string multiple times to achieve desired indentation. The task of repeating a string in C# can be accomplished using various methods.
One approach is to utilize the String.Repeat() method, which duplicates a specified string a given number of times. It takes a string as its first argument and the number of repetitions as its second. For instance:
string indent = "---"; Console.WriteLine(indent.Repeat(0)); // Outputs an empty string Console.WriteLine(indent.Repeat(1)); // Outputs "---" Console.WriteLine(indent.Repeat(2)); // Outputs "------" Console.WriteLine(indent.Repeat(3)); // Outputs "---------"
Alternatively, you can use the string constructor that accepts a character and the repetition count. This is particularly useful when repeating the same character.
string result = new String('-', 5); Console.WriteLine(result); // Outputs "-----"
This method simplifies the process of repeating specific characters for indentation purposes. You can replace the dash character with the desired indentation symbol and adjust the repetition count based on the item's depth.
The above is the detailed content of How Can I Repeat a String Multiple Times for Indentation in C#?. For more information, please follow other related articles on the PHP Chinese website!