C#String.PadLeft函數,文本對齊以及填補解決方案。

來源:互聯網
上載者:User

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

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.