Home >Backend Development >C++ >How Can I Efficiently Repeat a String Multiple Times in C#?
Simplifying String Repetition with String Builders
The task of inserting indentations before a string can be simplified by repeating a string a specified number of times. To efficiently achieve this, consider utilizing the String.Repeat method.
String.Repeat
The String.Repeat method takes a single string parameter and an integer representing the desired number of repetitions. It returns a new string with the original string concatenated upon itself the specified number of times.
Usage
Here's an example of using String.Repeat to create a variable number of indentations:
// Define the indentation string string indent = "---"; // Repeat the indentation string based on an item's depth int depth = 3; string indentation = indent.Repeat(depth); // Display the indented string Console.WriteLine(indentation + "Example String");
In this example, the indentation variable is assigned a string with three dashes, and the indented string is displayed with three levels of indentation.
String Constructor
An alternative approach for repeating a single character is using the String constructor that takes a character and the number of repetitions.
// Repeat a dash five times char dash = '-'; int repetitions = 5; string result = new String(dash, repetitions);
This approach is particularly convenient when repeating a single non-alphanumeric character, resulting in a string of a specified length filled with the character.
The above is the detailed content of How Can I Efficiently Repeat a String Multiple Times in C#?. For more information, please follow other related articles on the PHP Chinese website!