在 C# 中是否有更简单的方法来格式化具有精确长度的字符串?

我需要将字符串格式化为恰好 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)


繁华开满天机
浏览 197回答 3
3回答

MM们

您可以向字符串添加一个扩展方法,它会为您做到这一点: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);    }}

千巷猫影

尝试 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"

哈士奇WWW

您可以使用填充创建扩展方法:public static class StringExtensions{    public static string SubstringExact(this string src, int start, int length)     {         return src.PadRight(start + length).Substring(start, length);    } } 
打开App,查看更多内容
随时随地看视频慕课网APP