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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17249593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:57:40  来源:igfitidea点击:

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

c#

提问by

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?

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

回答by Zbigniew

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

确保长度不会超过LongTitlenull跳过检查):

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

回答by cuongle

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

回答by Peter Rasmussen

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

如果字符串长度大于 20,则使用 20,否则使用长度。

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

回答by AgentFire

Shortest, the:

最短的是:

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

回答by Sebastian

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

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

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

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

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