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

时间:2010-09-29 21:24:13

标签: c# arrays string limit

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

string foo = "1234567890";

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

11 个答案:

答案 0 :(得分:65)

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

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

const int MaxLength = 5;


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

答案 1 :(得分: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);
      }
   }
}

结果:

  

limit5 - q
limit10 - The   快速
limit100 - 快速棕色   狐狸跳过懒狗。

答案 2 :(得分:16)

你做不到。请注意foostring类型的变量

您可以创建自己的类型,例如BoundedString,然后:

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

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

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

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

在你更大的背景下,这对你有帮助吗?

答案 3 :(得分: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;
     }
   }
}

答案 4 :(得分:5)

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

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

答案 5 :(得分:3)

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

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

答案 6 :(得分:2)

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

答案 7 :(得分:2)

您可以尝试这样:

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

答案 8 :(得分:1)

如果您将if语句填充到要限制它的长度,则可以避免使用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

如果在使用substring

之前需要检查长度,则为no

答案 9 :(得分:0)

使用删除() ...

string foo = "1234567890";
int trimLength = 5;

if (foo.Length > trimLength) foo = foo.Remove(trimLength);

// foo is now "12345"

答案 10 :(得分:-1)

foo = foo.Substring(0,5);

相关问题