Replace all occurrences of the 'find' string with the 'replace' string. - CSharp System

CSharp examples for System:String Replace

Description

Replace all occurrences of the 'find' string with the 'replace' string.

Demo Code


using System.Collections;
using System.Text;
using System;//  w ww . j a v a  2  s.  c o m

public class Main{
        #endregion ZeroFill Method

        #region Replace Method

        /// <summary>
        /// Replace all occurrences of the 'find' string with the 'replace' string.
        /// </summary>
        /// <param name="source">Original string</param>
        /// <param name="find">String to find within the original string</param>
        /// <param name="replace">String to be used in place of the find string</param>
        /// <returns>Final string after all instances have been replaced.</returns>
        public static string Replace(string source, string find, string replace)
        {
            int i;
            int iStart = 0;

            if (source == string.Empty || source == null || find == string.Empty || find == null)
                return source;

            while (true)
            {
                i = source.IndexOf(find, iStart);
                if (i < 0) break;

                if (i > 0)
                    source = source.Substring(0, i) + replace + source.Substring(i + find.Length);
                else
                    source = replace + source.Substring(i + find.Length);

                iStart = i + replace.Length;
            }
            return source;
        }
}

Related Tutorials