【发布时间】:2011-04-19 01:35:01
【问题描述】:
我只是想知道如何在 C# 中限制字符串的长度。
string foo = "1234567890";
假设我们有。如何限制 foo 说 5 个字符?
【问题讨论】:
-
你能提供更多的上下文吗?你想在哪里做这个?在最简单的情况下,只需执行
if (foo.Length > 5) { throw new Lemmons.StringTooLongException(); }
我只是想知道如何在 C# 中限制字符串的长度。
string foo = "1234567890";
假设我们有。如何限制 foo 说 5 个字符?
【问题讨论】:
if (foo.Length > 5) { throw new Lemmons.StringTooLongException(); }
C# 中的字符串是不可变的,在某种意义上这意味着它们是固定大小的。
但是,您不能约束一个字符串变量只接受 n 个字符的字符串。如果你定义一个字符串变量,它可以被赋值为any字符串。如果截断字符串(或抛出错误)是业务逻辑的重要组成部分,请考虑在特定类的属性设置器中这样做(这是 Jon 建议的,它是在 .NET 中创建值约束的最自然方式)。
如果您只是想确保不会太长(例如,将其作为参数传递给某些遗留代码时),请手动截断它:
const int MaxLength = 5;
var name = "Christopher";
if (name.Length > MaxLength)
name = name.Substring(0, MaxLength); // name = "Chris"
【讨论】:
你可以扩展“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 - 快速棕色 狐狸跳过了那只懒狗。
【讨论】:
Substring 将抛出异常。
你不能。请记住,foo 是string 类型的变量。
您可以创建自己的类型,例如 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;
}
}
这对您的更大环境有帮助吗?
【讨论】:
char[] blah = new char[100];。你应该?不可以。使用字符串并通过包装类或严格定义的接口(最好是后者)强制执行大小约束。
BoundedString 似乎是从 string 到 BoundedString 的隐式转换运算符的不错选择。
string shortFoo = foo.Length > 5 ? foo.Substring(0, 5) : foo;
请注意,您不能只使用 foo.Substring(0, 5) 本身,因为它会在 foo 少于 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;
}
}
}
【讨论】:
如果你将 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 语句来检查长度
【讨论】:
你可以这样试试:
var x= str== null
? string.Empty
: str.Substring(0, Math.Min(5, str.Length));
【讨论】:
这是此问题的另一个替代答案。这种扩展方法效果很好。这解决了字符串比最大长度短并且最大长度为负的问题。
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));
}
【讨论】:
我能看到这个目的的唯一原因是数据库存储。如果是这样,为什么不让 DB 处理它,然后将异常推送到上游以在表示层处理?
【讨论】:
使用 Remove()...
string foo = "1234567890";
int trimLength = 5;
if (foo.Length > trimLength) foo = foo.Remove(trimLength);
// foo is now "12345"
【讨论】:
foo = foo.Substring(0,5);
【讨论】: