【问题标题】:Avoid exception with C# Substring() method? [duplicate]使用 C# Substring() 方法避免异常? [复制]
【发布时间】:2018-01-09 11:12:49
【问题描述】:

是否有其他方式或正确的方式来使用 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

我也尝试了许多替代方案和文档。我的结论是没有更好的解决方案,或者我需要编写自己的格式化程序,但我想听听你的意见。

【问题讨论】:

    标签: c# string


    【解决方案1】:

    您可以编写一个为您执行逻辑的扩展方法吗?

    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));
    

    ?

    【讨论】:

    • 甚至更短 - => value.Substring(0, Math.Min(length, value.Length));
    • @Zohar Peled,聪明
    • @BastienVandamme 确实,但不是我的 :-) 投票为重复。
    • 另外,刚刚注意到一个类型 - length.Substring(0, length) 应该是 value.Substring(0, length)
    • 并避免空异常 "value?.Substring(0, Math.Min(length, value.Length));"
    【解决方案2】:

    不会保存很多可打印的字符,但看起来更整洁

    $"{prefix.Substring(0, Math.Min(4, prefix.Length))}"
    

    【讨论】:

      【解决方案3】:

      您可以编写一个扩展方法,这样您就不必一遍又一遍地重复相同的逻辑:

      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));
      

      【讨论】:

        猜你喜欢
        • 2021-11-26
        • 1970-01-01
        • 1970-01-01
        • 2021-11-19
        • 2010-09-29
        • 1970-01-01
        • 2014-03-29
        相关资源
        最近更新 更多