3 回答
TA贡献1886条经验 获得超2个赞
您可以向字符串添加一个扩展方法,它会为您做到这一点:
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);
}
}
TA贡献1829条经验 获得超7个赞
尝试 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"
TA贡献1799条经验 获得超6个赞
您可以使用填充创建扩展方法:
public static class StringExtensions
{
public static string SubstringExact(this string src, int start, int length)
{
return src.PadRight(start + length).Substring(start, length);
}
}
- 3 回答
- 0 关注
- 196 浏览
添加回答
举报