【问题标题】:C#: Limit the length of a string? [duplicate]C#:限制字符串的长度? [复制]
【发布时间】:2011-04-19 01:35:01
【问题描述】:

我只是想知道如何在 C# 中限制字符串的长度。

string foo = "1234567890";

假设我们有。如何限制 foo 说 5 个字符?

【问题讨论】:

  • 你能提供更多的上下文吗?你想在哪里做这个?在最简单的情况下,只需执行if (foo.Length > 5) { throw new Lemmons.StringTooLongException(); }

标签: c# arrays string limit


【解决方案1】:

C# 中的字符串是不可变的,在某种意义上这意味着它们是固定大小的。
但是,您不能约束一个字符串变量只接受 n 个字符的字符串。如果你定义一个字符串变量,它可以被赋值为any字符串。如果截断字符串(或抛出错误)是业务逻辑的重要组成部分,请考虑在特定类的属性设置器中这样做(这是 Jon 建议的,它是在 .NET 中创建值约束的最自然方式)。

如果您只是想确保不会太长(例如,将其作为参数传递给某些遗留代码时),请手动截断它:

const int MaxLength = 5;


var name = "Christopher";
if (name.Length > MaxLength)
    name = name.Substring(0, MaxLength); // name = "Chris"

【讨论】:

  • 我会说 all 字符串在 .NET 中是固定长度的。但是你不能声明一个变量只能接受一定长度的字符串。
  • 是的,没错。我会修改我的回复,谢谢。
  • 如果字符串末尾有代理对,低代理被切断,那不会产生错误吗?
  • 如果 C# 足够聪明,可以选择正确的字母将“Jonathan”截断为“John”,我会感到非常惊讶。大多数语言可能只会给你“Jona”......
  • @Carl:哎呀,你当然是对的。
【解决方案2】:

你可以扩展“string”类来让你返回一个有限的字符串。

using System;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         // since specified strings are treated on the fly as string objects...
         string limit5 = "The quick brown fox jumped over the lazy dog.".LimitLength(5);
         string limit10 = "The quick brown fox jumped over the lazy dog.".LimitLength(10);
         // this line should return us the entire contents of the test string
         string limit100 = "The quick brown fox jumped over the lazy dog.".LimitLength(100);

         Console.WriteLine("limit5   - {0}", limit5);
         Console.WriteLine("limit10  - {0}", limit10);
         Console.WriteLine("limit100 - {0}", limit100);

         Console.ReadLine();
      }
   }

   public static class StringExtensions
   {
      /// <summary>
      /// Method that limits the length of text to a defined length.
      /// </summary>
      /// <param name="source">The source text.</param>
      /// <param name="maxLength">The maximum limit of the string to return.</param>
      public static string LimitLength(this string source, int maxLength)
      {
         if (source.Length <= maxLength)
         {
            return source;
         }

         return source.Substring(0, maxLength);
      }
   }
}

结果:

limit5 - q
limit10 - quick
limit100 - 快速棕色 狐狸跳过了那只懒狗。

【讨论】:

  • 我不明白,你为什么要麻烦检查。你不能直接返回 source.Substring(0, maxLength); 吗?我错过了什么吗?
  • @DonnyV。 - 如果任一参数超出字符串范围,Substring 将抛出异常。
  • 不敢相信我没看到……明白了
  • 当 maxLength 为负值 (msdn.microsoft.com/en-us/library/aka44szs.aspx) 或 source 为 null 时,这将失败
  • 字符串可以为空...
【解决方案3】:

你不能。请记住,foostring 类型的变量

您可以创建自己的类型,例如 BoundedString,并拥有:

BoundedString foo = new BoundedString(5);
foo.Text = "hello"; // Fine
foo.Text = "naughty"; // Throw an exception or perhaps truncate the string

...但是您不能阻止将字符串变量设置为任何字符串引用(或 null)。

当然,如果你有一个字符串property,你可以这样做:

private string foo;
public string Foo
{
    get { return foo; }
    set
    {
        if (value.Length > 5)
        {
            throw new ArgumentException("value");
        }
        foo = value;
    }
}

这对您的更大环境有帮助吗?

【讨论】:

  • 我可以做一个有限的字符数组吗?就像在 C/C++ 中一样?例如:char blah[100];
  • 当然char[] blah = new char[100];。你应该?不可以。使用字符串并通过包装类或严格定义的接口(最好是后者)强制执行大小约束。
  • BoundedString 似乎是从 stringBoundedString 的隐式转换运算符的不错选择。
【解决方案4】:

string shortFoo = foo.Length &gt; 5 ? foo.Substring(0, 5) : foo;

请注意,您不能只使用 foo.Substring(0, 5) 本身,因为它会在 foo 少于 5 个字符时抛出错误。

【讨论】:

    【解决方案5】:

    如果这是在类属性中,您可以在 setter 中进行:

    public class FooClass
    {
       private string foo;
       public string Foo
       {
         get { return foo; }
         set
         {
           if(!string.IsNullOrEmpty(value) && value.Length>5)
           {
                foo=value.Substring(0,5);
           }
           else
                foo=value;
         }
       }
    }
    

    【讨论】:

      【解决方案6】:

      如果你将 if 语句填充到你想要限制的长度,你可以避免它。

      string name1 = "Christopher";
      string name2 = "Jay";
      int maxLength = 5;
      
      name1 = name1.PadRight(maxLength).Substring(0, maxLength);
      name2 = name2.PadRight(maxLength).Substring(0, maxLength);
      

      name1 将拥有 Chris

      name2 将拥有 Jay

      在使用子字符串之前不需要 if 语句来检查长度

      【讨论】:

      • 当 text.Length 小于 maxLength 时,使用 .Trim() 删除 .PadRight(maxlength) 添加的空格,例如"01234567890123456789".PadRight(30).Substring(0, 30).Trim()
      【解决方案7】:

      你可以这样试试:

      var x= str== null 
              ? string.Empty 
              : str.Substring(0, Math.Min(5, str.Length));
      

      【讨论】:

        【解决方案8】:

        这是此问题的另一个替代答案。这种扩展方法效果很好。这解决了字符串比最大长度短并且最大长度为负的问题。

        public static string Left( this string str, int length ) {
          if (str == null)
            return str;
          return str.Substring(0, Math.Min(Math.Abs(length), str.Length));
        }
        

        另一种解决方案是将长度限制为非负值,并且仅将负值归零。

        public static string Left( this string str, int length ) {
          if (str == null)
            return str;
          return str.Substring(0, Math.Min(Math.Max(0,length), str.Length));
        }
        

        【讨论】:

          【解决方案9】:

          我能看到这个目的的唯一原因是数据库存储。如果是这样,为什么不让 DB 处理它,然后将异常推送到上游以在表示层处理?

          【讨论】:

          • Sql Server 会默默地截断它们,所以我正在考虑为此目的构建自己的类。 stackoverflow.com/questions/4628140/…
          • 如果我希望能够在不花费时间往返于数据库的情况下处理该截断,该怎么办(这可能会失败并出现不指示哪一列被截断的错误)
          【解决方案10】:

          使用 Remove()...

          string foo = "1234567890";
          int trimLength = 5;
          
          if (foo.Length > trimLength) foo = foo.Remove(trimLength);
          
          // foo is now "12345"
          

          【讨论】:

            【解决方案11】:

            foo = foo.Substring(0,5);

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多