Monday, February 25, 2019

A more forgiving c# replace a character in a string extension method ReplaceAt

Lately, I have seen this function replicated all over the inter-webs, all without some basic bounds checking. 

Here's a more forgiving C# replace a character in a string "ReplaceAt" string extension method.


        /// <summary>
        /// Change a character in string, using zero-based char[]. This implementation is faster than string builder.
        /// </summary>
        /// <param name="s">input string</param>
        /// <param name="idx">index</param>
        /// <param name="replaceChar">replacement character</param>
        /// <returns></returns>
        public static string ReplaceAt(this string s, uint idx, char replaceChar)
        {
            if (string.IsNullOrEmpty(s) || idx >= s.Length)
                return s;

            char[] chars = s.ToCharArray();
            chars[idx] = replaceChar;
            return new string(chars);
        }

No comments:

Post a Comment