C#String.PadLeft函数,文本对齐以及填补解决方案

 

由于很多时候我们需要把数据进行格式化,方便各个系统之间通信和数据交互,因此难免会经常让人位数不够而进行位数相应数据填充。比如,你希望获取的是7位的2进制数据格式,而2进制数据格式,都是以0,1都为数据信号的,只有1,0两数据格式,刚我说的是7位,相当于如下:1000101格式,如果,我的数据是101三个长度的2进制数据,但我想返回一个新的并且具有固定长度,位数不够填充0的做法。

string SourceStr="101";

string DestinationStr;

DestinationStr=String.PadLeft(7,"0");

Console.Write(DestinationStr);

以上代码就会输出:0000101

现在解析此函数,此函数有2个重载版本。

重载1:public string PadLeft(int totalWidth);

重载2public string PadLeft(int totalWidth, char paddingChar);

关于重载1的解释,微软的注释为:(这个默认是以空格进行左边填充,保持右边对齐。)

//
   
// Summary:
   
//
     Right-aligns the characters in this instance, padding with spaces on the
   
//
     left for a specified total length.
   
//

   
// Parameters:
   
//
   totalWidth:
   
//
     The number of characters in the resulting string, equal to the number of
   
//
     original characters plus any additional padding characters.
   
//

   
// Returns:
   
//
     A new System.String that is equivalent to this instance, but right-aligned
   
//
     and padded on the left with as many spaces as needed to create a length of
   
//
     totalWidth. Or, if totalWidth is less than the length of this instance, a
   
//
     new System.String object that is identical to this instance.
   
//

   
// Exceptions:
   
//
   System.ArgumentOutOfRangeException:
   
//     totalWidth is less than zero.

    public string PadLeft(int totalWidth);

而重载2的注释为:(可以根据自己想要填充的字符进行填充,对齐是字符串右对齐。)

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值