我需要将字符串格式化为恰好 x 个字符,但我格式化的值可以是任意长度。
"" => " "
"New York" => "New York "
"New York City" => "New York C"
目前,我正在这样做:
$"{(address.City.Substring(0, address.City.Length > 20 ? 20 : address.City.Length)),20}"
但是我做的越多,这变得非常乏味且容易出错:
var builder = new StringBuilder();
builder.AppendLine($"{(address.Street1.Substring(0, address.Street1.Length > 30 ? 30 : address.Street1.Length)),30}");
builder.AppendLine($"{(address.Street2.Substring(0, address.Street2.Length > 30 ? 30 : address.Street2.Length)),30}");
builder.AppendLine($"{(address.City.Substring(0, address.City.Length > 20 ? 20 : address.City.Length)),20}");
builder.AppendLine($"{(address.State.Substring(0, address.State.Length > 5 ? 5 : address.State.Length)),5}");
builder.AppendLine($"{(address.Zip.Substring(0, address.Zip.Length > 10 ? 10 : address.Zip.Length)),10}");
var result = builder.ToString();
我还有大约 30 件其他事情需要做这件事。如果有这样的东西,那就太好了:
address.City.SubstringExact(0, 20)
MM们
千巷猫影
哈士奇WWW
相关分类