String Truncating Extension

// December 20th, 2009 // Useful Code

This is a simple extension to truncate strings on whole words. If it can not find a whole word to truncate on then it will fall back to breaking a word up. You can also pass a string to append to the end of the truncated string. Other then that there is not a whole lot to say about this one.

//Code


        /// <summary>
        /// TRUNCATES A STRING PREFERRING WHOLE WORD OVER NON WHOLE WORD
        /// </summary>
        /// <param name="s">INCOMING STRING TO TRUNCATE</param>
        /// <param name="len">LENGTH IN WHICH TO TRUNCATE TO</param>
        /// <param name="postTruncate">ANYTHING TO ADD TO A TRUNCATED STRING SUCH AS ...</param>
        /// <returns>TRUNCATED STRING WITH POST TRUNCATE ADDED TO IT</returns>
        public static string Truncate(this string s, int len, string postTruncate)
        {
            //IF THE STRING IS SMALLER THEN THE LENGTH JUST RETURN THE STRING
            if (s == null || s.Length < len)
                return s;
            else
            {
                //INCASE NULL HAS BEEN PASSED IN CHANGE IT TO EMPTY STRING SO IT HAS A COUNT
                if (postTruncate == null)
                    postTruncate = string.Empty;

                //RETURN THE TRUNCATED STRING BACK TO CALLING FUNCTION
                string tmpReturn = string.Concat(Regex.Match(String.Concat(s, " "), string.Format("^(?<tmpMatch>.{{0,{0}}})\\s", len)).Groups["tmpMatch"].Value, postTruncate);

                //IF THE WHOLE WORD TRUNCATE WORKED THEN USE IT OTHERWISE USE NON WHOLE WORD TRUNCATE
                if (tmpReturn != postTruncate)
                    return tmpReturn;
                else
                    return string.Concat(Regex.Match(String.Concat(s, " "), string.Format("^(?<tmpMatch>.{{0,{0}}})", len)).Groups["tmpMatch"].Value, postTruncate);
            }
        }

//Usage


    class Program
    {
        static void Main(string[] args)
        {
            //OUTPUT WILL BE "Hello, World..."
            Console.WriteLine("Hello, World this is some long text to truncate".Truncate(15, "..."));
            Console.ReadLine();
        }
    }
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt