公告: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的用法和這個也是完全相似,只是這個是在後面補充,或者填充自己想要的字元。