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

前端 未结 11 682
陌清茗
陌清茗 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:26

    All very good answers, but to clean it up just a little, if your strings are sentences, don't break your string in the middle of a word.

    private string TruncateForDisplay(this string value, int length)
    {
      if (string.IsNullOrEmpty(value)) return string.Empty;
      var returnValue = value;
      if (value.Length > length)
      {
        var tmp = value.Substring(0, length) ;
        if (tmp.LastIndexOf(' ') > 0)
           returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ...";
      }                
      return returnValue;
    }
    

提交回复
热议问题