Extensions - Strings 1/22/2010 All Extensions posts

ReplaceEx

Replace a string using an expression.

        public static string ReplaceEx(this string original, string pattern, string replacement)
        {
            int count = 0;
            int position0 = 0;
            int position1 = 0;

            string upperString = original.ToUpper();
            string upperPattern = pattern.ToUpper();

            int inc = (original.Length / pattern.Length) * (replacement.Length - pattern.Length);

            char[] chars = new char[original.Length + Math.Max(0, inc)];

            while ((position1 = upperString.IndexOf(upperPattern, position0)) != -1)
            {
                for (int i = position0; i < position1; ++i)
                    chars[count++] = original[i];
                for (int i = 0; i < replacement.Length; ++i)
                    chars[count++] = replacement[i];
            
                position0 = position1 + pattern.Length;
            }

            if (position0 == 0) return original;
            
            for (int i = position0; i < original.Length; ++i)
                chars[count++] = original[i];

            return new string(chars, 0, count);
        }
 

TruncateHtml

Truncate a string and remove HTML. This is useful for message boards, articles, etc, where you just want to show a portion of the text and the user would click into it to read more.

        public static string TruncateHtml(this string html, int max)
        {
            string result = Regex.Replace(html, @"<(.|\n)*?>", string.Empty);

            return Truncate(result, max);
        }
 

Truncate

Truncates a string

        public static string Truncate(this string text, int max)
        {
            string result = text;

            if (result.Length > max) result = result.Substring(0, max - 3) + "...";
            return result;
        }