Tiny way to get the first 25 characters

后端 未结 12 1516
感动是毒
感动是毒 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!

    0 讨论(0)
  • 2020-12-29 13:54

    I'd stick with what you have tbh, but just as an alternative, if you have LINQ to objects you could

    new string(this.Description.ToCharArray().Take(25).ToArray())
    
    //And to maintain the ...
    + (this.Description.Length <= 25 ? String.Empty : "...")
    

    As others have said, you'd likely want to store 25 in a constant

    0 讨论(0)
  • 2020-12-29 13:55
    return this.Description.Substring(0, Math.Min(this.Description.Length, 25));
    

    Doesn't have the ... part. Your way is probably the best, actually.

    0 讨论(0)
  • 2020-12-29 13:57

    Looks fine to me, being really picky I would replace "..." with the entity reference "&hellip;"

    0 讨论(0)
  • 2020-12-29 13:59

    without .... this should be the shortest :

    public string ShortDescription
    {
        get { return Microsoft.VisualBasic.Left(this.Description;}
    }
    
    0 讨论(0)
  • 2020-12-29 13:59

    One way to do it:

    int length = Math.Min(Description.Length, 25);
    return Description.Substring(0, length) + "...";
    

    There are two lines instead of one, but shorter ones :).

    Edit: As pointed out in the comments, this gets you the ... all the time, so the answer was wrong. Correcting it means we go back to the original solution.

    At this point, I think using string extensions is the only option to shorten the code. And that makes sense only when that code is repeated in at least a few places...

    0 讨论(0)
提交回复
热议问题