Monthly Archives: September 2012

Trimming .NET 4.0

Here is two string extension methods, one to handle the change of functionality in the Trim() method from .NET 3.5 to 4.0. The other one removes null characters from a string.

 

public static class Extensions
    {
        //
http://www.blogfor.net/2010/08/01/string-trim-treats-unicode-whitespace-differently-in-net-4/
        public static string TrimWithUnicodeWhitespace(this string stringToTrim)
        {
            return stringToTrim.Trim().Trim(new char[] { ‘\uFEFF’, ‘\u200B’ });
        }

        public static string TrimWithNullChar(this string stringToTrim)
        {
            char nullChar = Convert.ToChar(0x0);
            int i = stringToTrim.IndexOf(nullChar);
            if (i > 0)
            {
                stringToTrim = stringToTrim.Substring(0, i);
            }
            return stringToTrim.Trim();
        }
    }