Case insensitive replace - CSharp System

CSharp examples for System:String Case

Description

Case insensitive replace

Demo Code


using System.Text;
using System;//from www . ja  v  a 2  s. c  om

public class Main{
        /// <summary>
        ///   <para>Case insensitive replace</para>
        /// </summary>
        /// <param name = "text">Incoming text string</param>
        /// <param name = "oldValue">Token to be replaced</param>
        /// <param name = "newValue">Replacement token</param>
        /// <param name = "comparisonType">Comparison provider</param>
        /// <returns>Resultant text</returns>
        public static string Replace(this string text, string oldValue, string newValue, StringComparison comparisonType)
        {
            if (text == null)
            {
                return null;
            }

            if (String.IsNullOrEmpty(oldValue))
            {
                return text;
            }

            var length = oldValue.Length;
            var patternIndex = -1;
            var lastIndex = 0;
            var result = new StringBuilder();

            while (true)
            {
                patternIndex = text.IndexOf(oldValue, patternIndex + 1, comparisonType);

                if (patternIndex < 0)
                {
                    result.Append(text, lastIndex, text.Length - lastIndex);

                    break;
                }

                result.Append(text, lastIndex, patternIndex - lastIndex);
                result.Append(newValue);

                lastIndex = patternIndex + length;
            }

            return result.ToString();
        }
}

Related Tutorials