由於很多時候我們需要把數據進行格式化,方便各個系統之間通信和數據交互,因此難免會經常讓人位數不夠而進行位數相應數據填充。比如,你希望獲取的是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.
//