Thursday, January 24, 2013

String Truncate

PROBLEM: The .NET framework doesn't have a truncate method for strings.  Substring will fail if you're not careful (i.e. if you don't check that the string has at least as many characters at the truncation length)

SOLUTION: Add a Truncate extension method for the string class that does the boring checks (length, null - some other examples don't include the null check, etc) for you each time.


        /// <summary>
        /// Ensure that a string is no longer than a specified maximum number of characters.
        /// This string extension method has been written because there is no string truncate method
        /// in the .NET framework and Substring will throw an exception if the length you enter is
        /// longer than the length of the string.
        /// </summary>
        /// <param name="originalString"></param>
        /// <param name="maximumLength"></param>
        /// <returns></returns>
        public static string Truncate(this String originalString, int maximumLength)
        {
            return (originalString == null || originalString.Length <= maximumLength) ? originalString : originalString.Substring(0, maximumLength);
        }

Example use:

          string newString = oldString.Truncate(10);

Credit goes to this guy and one of the people in his comments: http://jamesfricker.blogspot.com.au/2007/08/truncating-string-in-c-easy-huh.html

No comments:

Post a Comment