简体   繁体   English

如何将字符串的长度限制为 150 个字符?

[英]How can I limit the length of a string to 150 characters?

I tried the following:我尝试了以下方法:

var a = description.Substring(0, 150);

However this gives a problem if the length of description is less than 150 chars.但是,如果描述的长度小于 150 个字符,则会出现问题。 So is there another way I can limit the length to 150 that won't give an error when string length is for example 20.那么是否有另一种方法可以将长度限制为 150,当字符串长度为 20 时不会出错。

var a = description == null 
        ? string.Empty 
        : description.Substring(0, Math.Min(150, description.Length));
var a = description.Substring(0, Math.Min(150, description.Length));

只需抓取150个字符的子字符串,或整个字符串,以较短者为准。

Try the following extension method 请尝试以下扩展方法

public static string LimitTo(this string data, int length) {
  return (data == null || data.Length < length) 
    ? data 
    : data.Substring(0, length);
}

The String Length Attribute works for C#: 字符串长度属性适用于C#:

[StringLength(150)]
public string MyProperty { get; set; }

I think you actually want this. 我想你真的想要这个。

public static string LimitTo(this string data, int length) {
  return (data == null || data.Length <= length)   // Less than or equal to
    ? data 
    : data.Substring(0, length);
}

It will be good if your environment support you to use below method. 如果您的环境支持您使用以下方法,那将是一件好事。 (As @christian-cody suggested.) (正如@ christian-cody建议的那样。)

[StringLength(150)]
public string MyProperty { get; set; }

You have to include the below namespace to use it. 您必须包含以下命名空间才能使用它。

using System.ComponentModel.DataAnnotations;

everyone seems to be overcomplicating this, all you need is simply 每个人似乎都过于复杂,所有你需要的只是简单

var a = description;
if (description.length > 150) a = description.Substring(0, 150);

sometimes you just need to think around the problem. 有时你只需要思考问题。

Strings are immutable, even if you could create an instance that worked the way you wanted, as soon as you assign another value to your variable, it would be a different instance of type string . 字符串是不可变的,即使您可以创建一个按照您想要的方式工作的实例,只要您为变量分配另一个值,它就是string类型的不同实例。

If you want a string property that has a max of 150 characters, then write a property where you check the value in the setter and throw an exception if it's more than 150 characters. 如果你想要一个最多包含150个字符的string属性,那么写一个属性来检查setter中的值,如果超过150个字符则抛出异常。

If you want a string parameter to a method that has a max of 150 characters, then at the top of the method, check to see if it is more than 150 characters, if it is, throw an exception. 如果你想要一个string参数到一个最多150个字符的方法,那么在方法的顶部,检查它是否超过150个字符,如果是,则抛出异常。

var a = description.Substring(0, description.Length > 150 ? 150 : description.Length);

As of C# 8.0 we can utilize the Range operator and end up with this:从 C# 8.0 开始,我们可以使用Range 运算符并得到以下结果:

var x = description[..150];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM