Friday, September 13, 2013

How to replace multiple characters from a string in C#

 static Dictionary<char, char> ToReplace = new Dictionary<char, char>() { { '*', ' ' }, { '%', ' ' } };

Here ToReplace dictionary contains all characters and its replacement as key value , here the char you want to replace is KEY and the KEY will be Replace with VALUE from the bellow function

 /// <summary>
        /// Funtion Name: ReplaceWildchars
        /// Bishnu Tewary
        /// 13-09-2013
        /// This function will replace wildchar from the string
        /// </summary>
        /// <param name="inputString">input string</param>
        /// <returns>retun string after replacing </returns>
        public string ReplaceWildchars(string inputString)
        {
            var tmpStr = inputString.Select(c =>
            {
                char r;
                if (ToReplace.TryGetValue(c, out r))
                    return r;
                return c;
            });
            return new string(tmpStr.ToArray()).Trim();
        }

No comments:

Post a Comment