In this post we will learn about Easy way to remove special characters from string. There are many ways available to achieve this like we can use string.replace method we can also use regex and many more but there should be a simple c# method that should take care about this
In this example I will show how we can create our custom method to replace special characters and plus point is we can add as many chars as we can which we don’t want to see in our string
So here we go, I will use linq in order to achieve this. Linq is fast and makes your life easy
public static string RemoveSpecialChars(string requestedString) { if (string.IsNullOrEmpty(requestedString)) return requestedString; var symbols = new[] { ",", ".", "/", "!", "@", "$", "%", "^", "&", "*", "'", """, ";", "_", "(", ")", ":", "|", "[", "]" }; return symbols.Aggregate(requestedString, (current, symbol) => current.Contains(symbol) ? current.Replace(symbol, String.Empty) : current); }
Benefits of Custom Method
There are many benefits of custom extension method that will allow you add your desired chars to exclude from string or you can also customize this method according to your needs and we’re using linq so its fast.
Hope you enjoyed it.