在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();
}
如有指正之處,歡迎隨時提出