Tiny way to get the first 25 characters

后端 未结 12 1572
感动是毒
感动是毒 2020-12-29 13:12

Can anyone think of a nicer way to do the following:

public string ShortDescription
{
    get { return this.Description.Length <= 25 ? this.Description :          


        
12条回答
  •  庸人自扰
    2020-12-29 13:53

    Well I know there's answer accepted already and I may get crucified for throwing out a regular expression here but this is how I usually do it:

    //may return more than 25 characters depending on where in the string 25 characters is at
    public string ShortDescription(string val)
    {
        return Regex.Replace(val, @"(.{25})[^\s]*.*","$1...");
    }
    // stricter version that only returns 25 characters, plus 3 for ...
    public string ShortDescriptionStrict(string val)
    {
        return Regex.Replace(val, @"(.{25}).*","$1...");
    }
    

    It has the nice side benefit of not cutting a word in half as it always stops after the first whitespace character past 25 characters. (Of course if you need it to truncate text going into a database, that might be a problem.

    Downside, well I'm sure it's not the fastest solution possible.

    EDIT: replaced … with "..." since not sure if this solution is for the web!

提交回复
热议问题