C#:限制字符串的长度?

Lem*_*ons 43 c# arrays string limit

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

string foo = "1234567890";
Run Code Online (Sandbox Code Playgroud)

说我们有.我怎么能限制foo说5个字符?

Dan*_*mov 68

C#中的字符串是不可变的,在某种意义上它意味着它们是固定大小的.
但是,您不能将字符串变量约束为仅接受n个字符的字符串.如果定义字符串变量,则可以为其分配任何字符串.如果截断字符串(或抛出错误)是业务逻辑的重要组成部分,请考虑在特定类的属性设置器中执行此操作(这是Jon建议的,这是在.NET中创建值的最自然的方法).

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

const int MaxLength = 5;


var name = "Christopher";
if (name.Length > MaxLength)
    name = name.Substring(0, MaxLength); // name = "Chris"
Run Code Online (Sandbox Code Playgroud)

  • 我会说*所有*字符串在.NET中是固定长度的.但是你不能声明一个*变量*只能接受一定长度的字符串. (3认同)

Mic*_*ael 34

您可以扩展"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);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

结果:

limit5 - q
limit10 - 快速
限制100 - 快速的棕色狐狸跳过懒狗.

  • @DonnyV. - 如果任一参数超出字符串的边界,`Substring`将抛出异常. (5认同)

Jon*_*eet 16

你不能.请记住,这foo是一个类型的变量string.

你可以创建自己的类型BoundedString,并且拥有:

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

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

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

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

无论你的大背景如何,这对你有帮助吗?

  • 当然`char [] blah = new char [100];`.你应该?否.使用字符串并使用包装类或严格定义的接口(最好是后者)强制执行大小约束. (4认同)

jms*_*era 6

如果这是在类属性中,您可以在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;
     }
   }
}
Run Code Online (Sandbox Code Playgroud)


TTT*_*TTT 5

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

请注意,您不能仅使用foo.Substring(0,5),因为当foo小于5个字符时它会抛出错误.


Arc*_*l33 5

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

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));
}
Run Code Online (Sandbox Code Playgroud)

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

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));
}
Run Code Online (Sandbox Code Playgroud)


Rah*_*thi 5

你可以这样尝试:

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