如何将字符串限制为不超过一定长度?

时间:2013-06-22 10:18:03

标签: c#

我尝试了以下内容:

var Title = LongTitle.Substring(0,20)

如果LongTitle的长度小于20,则无效。如何将字符串限制为最多20个字符,但如果它们仅为5个字符长则不会出错?

5 个答案:

答案 0 :(得分:31)

确保长度不超过LongTitle(跳过null检查):

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

这可以转换为扩展方法:

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

可以用作:

string title = LongTitle.Truncate(20);

答案 1 :(得分:13)

最短,:

var title = longTitle.Substring(0, Math.Min(20, longTitle.Length))

答案 2 :(得分:8)

string title = new string(LongTitle.Take(20).ToArray());

答案 3 :(得分:5)

如果字符串Length大于20,请使用20,否则使用Length。

string  title = LongTitle.Substring(0,
    (LongTitle.Length > 20 ? 20 : LongTitle.Length));

答案 4 :(得分:3)

您可以使用StringLength属性。这样就不能存储比指定长度更长(或更短)的字符串。

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

[StringLength(20, ErrorMessage = "Your Message")]
public string LongTitle;