How can I limit a string to no more than a certain

2020-07-02 09:19发布

I tried the following:

var Title = LongTitle.Substring(0,20)

This works but not if LongTitle has a length of less than 20. How can I limit strings to a maximum of 20 characters but not get an error if they are just for example 5 characters long?

标签: c#
5条回答
Animai°情兽
2楼-- · 2020-07-02 09:57

If the string Length is bigger than 20, use 20, else use the Length.

string  title = LongTitle.Substring(0,
    (LongTitle.Length > 20 ? 20 : LongTitle.Length));
查看更多
Lonely孤独者°
3楼-- · 2020-07-02 09:59

You can use the StringLength attribute. That way no string can be stored that is longer (or shorter) than a specified length.

See: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.stringlengthattribute%28v=vs.100%29.aspx

[StringLength(20, ErrorMessage = "Your Message")]
public string LongTitle;
查看更多
一夜七次
4楼-- · 2020-07-02 10:01

Make sure that length won't exceed LongTitle (null checking skipped):

int maxLength = Math.Min(LongTitle.Length, 20);
string title = LongTitle.Substring(0, maxLength);

This can be turned into extension method:

public static class StringExtensions
{

    /// <summary>
    /// Truncates string so that it is no longer than the specified number of characters.
    /// </summary>
    /// <param name="str">String to truncate.</param>
    /// <param name="length">Maximum string length.</param>
    /// <returns>Original string or a truncated one if the original was too long.</returns>
    public static string Truncate(this string str, int length)
    {
        if(length < 0)
        {
            throw new ArgumentOutOfRangeException(nameof(length), "Length must be >= 0");
        }

        if (str == null)
        {
            return null;
        }

        int maxLength = Math.Min(str.Length, length);
        return str.Substring(0, maxLength);
    }
}

Which can be used as:

string title = LongTitle.Truncate(20);
查看更多
爷、活的狠高调
5楼-- · 2020-07-02 10:01
string title = new string(LongTitle.Take(20).ToArray());
查看更多
欢心
6楼-- · 2020-07-02 10:08

Shortest, the:

var title = longTitle.Substring(0, Math.Min(20, longTitle.Length))
查看更多
登录 后发表回答