How can I truncate my strings with a “…” if they are too long?

前端 未结 11 671
陌清茗
陌清茗 2020-12-13 23:13

Hope somebody has a good idea. I have strings like this:

abcdefg
abcde
abc

What I need is for them to be trucated to show like this if more

11条回答
  •  旧巷少年郎
    2020-12-13 23:23

    Maybe it is better to implement a method for that purpose:

    string shorten(sting yourStr)
    {
    //Suppose you have a string yourStr, toView and a constant value 
    
        string toView;
        const int maxView = 3;
    
        if (yourStr.Length > maxView)
            toView = yourStr.Substring(0, maxView) + " ..."; // all you have is to use Substring(int, int) .net method
        else
            toView = yourStr;
    return toView;
    }
    

提交回复
热议问题