[ C# 开发随笔 ] 数字左侧补0与字串右侧补足文字範例

试用一下ithome从我的点部落贴文章来测试一下。

在Coding常常会有需要补足字串,或者将流水序号补上0的状况发生,已前常常土砲直接用SubString跟IndexOf去解决,但事后发现 String 的 Api 本身就有很多这类的方法可以使用。接下来会示範 int 左侧补上0的範例跟 字串右侧补上空白的範例结果。

以下为 int 左侧补0之範例 

private static void Main(string[] args){    const int seq = 1;    // ** Use ToString fill 0    // Let seq string length is 3 to fill 0 in string left    var threeLengthStr = seq.ToString("000");    Console.WriteLine($"Use int.ToString('000') to fill 0 result : {threeLengthStr}");    // ** Use PasLeft fill 0    // Let seq string length is 3 to fill 0 in string left    var threeLengthStrUsePadLeft = seq.ToString().PadLeft(3, '0');    Console.WriteLine($"Use string.PadLeft(3,'0') to fill 0 result : {threeLengthStrUsePadLeft}");    // ** Use String.Format fill 0    // Let seq string length is 3 to fill 0 in string left    var threeLengthStrUseFormat = string.Format("{0:000}", seq);    Console.WriteLine($"Use string.Format() to fill 0 result : {threeLengthStrUseFormat}");    // ** Use String.Interpolation fill 0    // Let seq string length is 3 to fill 0 in string left    var threeLengthStrUseStringInterpolation = $"{seq:000}";    Console.WriteLine($"Use string Interpolation to fill 0 result : {threeLengthStrUseStringInterpolation}");    // Result    // Use int.ToString('000') to fill 0 result: 001    // Use string.PadLeft(3, '0') to fill 0 result: 001    // Use string.Format() to fill 0 result: 001    // Use string Interpolation to fill 0 result: 001    Console.Read();}

以下为 string 右侧侧补空白之範例 

private static void Main(string[] args){    const string sampleString = "CC001";    // ** Use PadRight fill space    // Let seq string length is 3 to fill 0 in string left    var padRightStr = sampleString.PadRight(10, ' ');    Console.WriteLine($"Use string.PasRight(10,'_') to fill space result : {padRightStr} ; Length: { padRightStr.Length}");    // ** Use String.Format fill space    // Let seq string length is 10 to fill space in string left    var formatString = String.Format("{0,-10}", sampleString);    Console.WriteLine($"Use string.Format() to fill space result : {formatString} ; Length: { formatString.Length}");    // ** Use String Interpolation fill space    // Let seq string length is 10 to fill space in string left    var interpolationStr = $"{sampleString,-10}";    Console.WriteLine($"Use string Interpolation to fill space result : {interpolationStr} ; Length:{interpolationStr.Length}");    // Result    // Use string.PasRight(10, '_') to fill space result : CC001; Length: 10    // Use string.Format() to fill space result : CC001; Length: 10    // Use string Interpolation to fill space result : CC001; Length: 10    Console.Read();}

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章