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

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

    Here's a version that accounts for the length of the ellipses:

        public static string Truncate(this string value, int maxChars)
        {
            const string ellipses = "...";
            return value.Length <= maxChars ? value : value.Substring(0, maxChars - ellipses.Length) + ellipses;
        }
    

提交回复
热议问题