Home >Backend Development >C++ >How Can I Efficiently Repeat a String Multiple Times in C#?

How Can I Efficiently Repeat a String Multiple Times in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-07 10:33:46196browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn