Substring with ellipses but OK if shorter, will take 3 characters off character count if necessary tries to land on a space. - CSharp System

CSharp examples for System:String Shorten

Description

Substring with ellipses but OK if shorter, will take 3 characters off character count if necessary tries to land on a space.

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System;//w  w  w. ja  v  a  2s.  c  o  m

public class Main{
        /// <summary>
        /// Substring with ellipses but OK if shorter, will take 3 characters off character count if necessary
        /// tries to land on a space.
        /// </summary>
        public static string LimitWithElipsesOnWordBoundary(this string str, int characterCount)
        {
            if (characterCount < 5) return str.Limit(characterCount);       // Can't do much with such a short limit
            if (str.Trim().Length <= characterCount)
                return str.Trim();
            if (str.Length <= characterCount - 3)
                return str;
            else
            {
                int lastspace = str.Substring(0, characterCount - 3).LastIndexOf(' ');
                if (lastspace > 0 && lastspace > characterCount - 10)
                {
                    return str.Substring(0, lastspace) + "...";
                }
                else
                {
                    // No suitable space was found
                    return str.Substring(0, characterCount - 3) + "...";
                }
            }
        }
        /// <summary>
        /// Substring but OK if shorter
        /// </summary>
        public static string Limit(this string str, int characterCount)
        {
            if (str.Trim().Length <= characterCount) return str.Trim();
            else return str.Substring(0, characterCount).TrimEnd(' ');
        }
}

Related Tutorials