Home > Backend Development > C++ > How Can I Efficiently Repeat a String Character for Indentation in C#?

How Can I Efficiently Repeat a String Character for Indentation in C#?

DDD
Release: 2025-01-07 10:38:40
Original
919 people have browsed it

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);
Copy after login

For example, to create an indentation string of five hyphens:

string indent = new String('-', 5);
Copy after login

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
Copy after login

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!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template