C#输出文本树形层次,前或者后自定义空格位数

本文介绍了一种在C#中使用String.PadLeft方法来实现字符串缩进的方法。通过该方法可以方便地生成带有固定数量空格的缩进字符串,从而实现文本的对齐效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Indent String with Spaces

This example shows how to indent strings using method for padding in C#. To repeat spaces use method String.PadLeft. If you call „hello“.PadLeft(10) you will get the string aligned to the right: „     hello“. If you use empty string instead of the „hello“ string the result will be 10× repeated space character. This can be used to create simple Indent method.

相应的可以使用String.PadRight实现右边填充固定位数的指定字符

The Indent method:

[C#]

public static string Indent(int count)
{
    return "".PadLeft(count);
}

Test code:

[C#]

Console.WriteLine(Indent(0) + "List");
Console.WriteLine(Indent(3) + "Item 1");
Console.WriteLine(Indent(6) + "Item 1.1"); Console.WriteLine(Indent(6) + "Item 1.2"); Console.WriteLine(Indent(3) + "Item 2"); Console.WriteLine(Indent(6) + "Item 2.1"); 

Output string:

List
   Item 1
      Item 1.1
      Item 1.2
   Item 2
      Item 2.1

转载于:https://www.cnblogs.com/coolsundy/p/5863215.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值