Truncate string on whole words in .NET C#

前端 未结 10 1373
走了就别回头了
走了就别回头了 2020-11-29 22:43

I am trying to truncate some long text in C#, but I don\'t want my string to be cut off part way through a word. Does anyone have a function that I can use to truncate my st

10条回答
  •  伪装坚强ぢ
    2020-11-29 23:24

    simplified, added trunking character option and made it an extension.

        public static string TruncateAtWord(this string value, int maxLength)
        {
            if (value == null || value.Trim().Length <= maxLength)
                return value;
    
            string ellipse = "...";
            char[] truncateChars = new char[] { ' ', ',' };
            int index = value.Trim().LastIndexOfAny(truncateChars);
    
            while ((index + ellipse.Length) > maxLength)
                index = value.Substring(0, index).Trim().LastIndexOfAny(truncateChars);
    
            if (index > 0)
                return value.Substring(0, index) + ellipse;
    
            return value.Substring(0, maxLength - ellipse.Length) + ellipse;
        }
    

提交回复
热议问题