Wednesday, March 13, 2019

"ReplaceAt" string extension method that handle null char '\0' properly

A better "ReplaceAt" string extension method that handle null char '\0' properly, by removing if from resultant string. Note : This does not fully support Unicode strings. It does partially, if the replacement index is before any Unicode string, otherwise not.

Update Thu 05-Sep-19  -  See UNICODE implementation - 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[] which is faster than string builder. '\0' will result in string.empty removal.
        /// </summary>
        /// <param name="s">input string</param>
        /// <param name="idx">index</param>
        /// <param name="replaceChar">replacement character</param>
        /// <returns>string with replaced character or null removed</returns>
        public static string ReplaceAt(this string s, int idx, char replaceChar)
        {
            if (string.IsNullOrEmpty(s) || idx >= s.Length || idx < 0) //not ideal want unint but takes too long
                return s;

            if (replaceChar == '\0')
                return s.Remove(idx, 1); 
            else
                return s.Remove(idx, 1).Insert(idx, replaceChar.ToString()); //in 1,483 ticks small string, 1,592 ticks for 50 char length

       }

No comments:

Post a Comment