[C#]根据索引替换字符/字符串

关键代码:

        #region 根据索引替换字符

        /// <summary>

        /// 根据索引替换字符

        /// <para>eg:Assert.AreEqual("ZBCDEFGHIJ", StringHelper.ReplaceAt("ABCDEFGHIJ",0,'Z'));</para>

        /// </summary>

        /// <param name="data">需要操作的字符串</param>

        /// <param name="index">目标索引</param>

        /// <param name="replace">替换成字符</param>

        /// <returns>操作后的字符串</returns>

        public static string ReplaceAt(this string data, int index, char replace)

        {

            StringBuilder _builder = new StringBuilder(data);

            _builder[index] = replace;

            return _builder.ToString();

        }

        #endregion

        #region 根据索引替换字符串

        /// <summary>

        /// 根据索引替换字符串

        /// <para>eg:Assert.AreEqual("ZXCDEFGHIJ", StringHelper.ReplaceAt("ABCDEFGHIJ", 0, 2, "ZX"));</para>

        /// </summary>

        /// <param name="data">需要操作的字符串</param>

        /// <param name="index">目标索引</param>

        /// <param name="length">需要替换长度</param>

        /// <param name="replace">替换成字符串</param>

        /// <returns>操作后的字符串</returns>

        public static string ReplaceAt(this string data, int index, int length, string replace)

        {

            StringBuilder _builder = new StringBuilder(data);

            _builder.Remove(index, length);

            _builder.Insert(index, replace);

            return _builder.ToString();

        }

        #endregion

希望有所帮助!

你可能感兴趣的:(字符串)