☆用心生活☆-wonder-{改变自己才能让自己过上不一样的日子。为自己加油!}

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

公告QQ群:124766907,若你是在.NET领域有独到见解,并有深厚的编程功力,在某一领域具有专长,欢迎本您入群,本群已经有好几位MVP,在SL,.NET,BS方面具有造诣的人欢迎进群。无4年以上经验者勿加,本群追寻高端顶级,多谢。

由于很多时候我们需要把数据进行格式化,方便各个系统之间通信和数据交互,因此难免会经常让人位数不够而进行位数相应数据填充。比如,你希望获取的是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的注释为:(可以根据自己想要填充的字符进行填充,对齐是字符串右对齐。)

 

代码
//
// Summary:
// Right-aligns the characters in this instance, padding on the left with a
// specified Unicode character 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.
//
// paddingChar:
// A Unicode padding character.
//
// Returns:
// A new System.String that is equivalent to this instance, but right-aligned
// and padded on the left with as many paddingChar characters as needed to create
// a length of totalWidth. Or, if totalWidth is less than the length of this
// instance, a new System.String that is identical to this instance.
//
// Exceptions:
// System.ArgumentOutOfRangeException:
// totalWidth is less than zero.
public string PadLeft(int totalWidth, char paddingChar);

同理关于PadRight的用法和这个也是完全相似,只是这个是在后面补充,或者填充自己想要的字符。

 

 

posted @ 2010-06-17 11:34  ☆用心生活☆  阅读(4487)  评论(0编辑  收藏  举报
本作者写的任何文章均属原创,若要转载,请注明出处;若
进行与文章有关的商业行为,本作者保留拥有诉诸法律追究
侵权的任何行为。文章只代表本人某一学习时间段内对某一
技术的说明,不代表具有绝对的正确性,若要学习,请与各
位高手编程人员讨论学习。本文章也不代表自己某一时期某
一公司的任何专著和机密文件。仅仅提供自我学习和他人学
习的文章参考,以及自我知识记录。wanzegui325#163.com