试用一下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();}