Home >Backend Development >C++ >How Can I Efficiently Repeat a String Character for Indentation in C#?
Repeating a String for Indentation
When indenting a string based on an item's depth, it's convenient to have an efficient way to return a string repeated a specified number of times.
Using the String Constructor
If you only intend to repeat the same character, you can use the String constructor that accepts a character and the number of times to repeat it:
string indent = new String(char c, int count);
For example, to create an indentation string of five hyphens:
string indent = new String('-', 5);
This will return the string "-----".
Example Usage
You can use this approach to easily generate indentations based on an item's depth:
int depth = 2; string indent = new String('-', depth); Console.WriteLine(indent + "Item at depth " + depth); Output: --Item at depth 2
The above is the detailed content of How Can I Efficiently Repeat a String Character for Indentation in C#?. For more information, please follow other related articles on the PHP Chinese website!