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.

Update Thu 05-Sep-19 - See full UNICODE version - https://metadataconsulting.blogspot.com/2019/08/C-Sharp-A-Faster-Unicode-ReplaceAt-method-that-works-with-surrogate-pairs-and-4-byte-Unicode-characters.html


        /// <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