我需要将字符串格式化为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)
答案 0 :(得分:5)
你可以只为字符串添加一个扩展方法,这样就可以了:
public static class StringExtensions
{
public static string ToLength(this string self, int length)
{
if(self == null)
return null;
return self.Length > length ? self.Substring(0, length) : self.PadRight(length);
}
}
答案 1 :(得分:1)
尝试str.PadRight(x, ' ').Substring(0, x);
string str1 = "";
string res1 = str1.PadRight(10, ' ').Substring(0, 10);
// " "
string str2 = "New York ";
string res2 = str2.PadRight(10, ' ').Substring(0, 10);
//"New York "
string str3 = "New York C";
string res3 = str3.PadRight(10, ' ').Substring(0, 10);
//"New York C"
答案 2 :(得分:0)
您可以使用填充创建扩展方法:
public static class StringExtensions
{
public static string SubstringExact(this string src, int start, int length)
{
return src.PadRight(start + length).Substring(start, length);
}
}