简体   繁体   中英

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. 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.

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#:

[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.)

[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 .

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.

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.

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:

var x = description[..150];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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