RemoveSpecialCharacters

/// <summary>
        /// Removes any special characters in the input string not provided in the allowed special character list. 
        /// </summary>
        /// <param name="input">Input string to process</param>
        /// <param name="allowedCharacters">list of allowed special characters </param>
        /// <returns></returns>
        public string RemoveSpecialCharacters(string input, string allowedCharacters)
        {
            char[] buffer = new char[input.Length];
            int index = 0;

            char[] allowedSpecialCharacters = allowedCharacters.ToCharArray();
            foreach (char c in input.Where(c => char.IsLetterOrDigit(c) || allowedSpecialCharacters.Any(x => x == c)))
            {
                buffer[index] = c;
                index++;
            }
            return new string(buffer, 0, index);
        }
Example:
// Remove carriage return from the input string
            var processedString = RemoveSpecialCharacters("Hello! This is string to process. \r\n", @""",-{}.! ");

Description

Sometimes it is required to remove some special characters like carriage return, or new line which can be considered as invalid characters, especially while file processing. This method removes any special characters in the input string which is not included in the allowed special character list.

Details

  • Author: Naveen V
  • Submitted on: 6/23/2015 3:56:16 AM
  • Language: C#
  • Type: string
  • Views: 1499

Double click on the code to select all.

 

;