是否有其他方法或正确的方法来使用SubString()
这是我的样本:
var prefix = "OKA";
Console.WriteLine($"{prefix.Substring(0, 4)}");
// Result: Index and length must refer to a location within the string.Parameter name: length
为了避免这种异常,我必须写下这样的东西:
var prefix = "OKA";
Console.WriteLine($"{prefix.Substring(0, prefix.Length > 4 ? 4 : prefix.Length)}");
// Result: OKA
这项工作但在您需要在代码中始终使用此技巧时变得难以阅读。
所以我有一些聪明的东西,我可以使用
var prefix = "OKA";
Console.WriteLine($"{prefix:XX}");
// XX is not working
我也尝试了很多替代和文档。我的结论是没有更好的解决方案,或者我需要编写自己的格式化程序,但我想听听你的意见。
答案 0 :(得分:6)
你可以写一个为你做逻辑的扩展方法吗?
static class SomeHelperClass
{
public static string Truncate(this string value, int length)
=> (value != null && value.Length > length) ? value.Substring(0, length) : value;
}
并使用
Console.WriteLine(prefix.Truncate(4));
答案 1 :(得分:2)
您可以编写扩展方法,这样您就不必一遍又一遍地重复相同的逻辑:
public static class StringExtensions
{
public static string Prefix(this string value, int length)
{
if (value.Length > length)
{
return value;
}
return value.SubString(0, length);
}
}
然后:
Console.WriteLine("OKA".Prefix(4));
答案 2 :(得分:0)
不保存许多可打印的字符,但它看起来更整洁
$"{prefix.Substring(0, Math.Min(4, prefix.Length))}"