I need a method that clean up a string considering these few rules:
- Remove or not Spaces
- Remove or not Special Chars
- Remove or not Numbers
- Descaptalize or not the string (this is don't really needed but I included it anyway).
I did some google if exists something that already do this, but found nothing, so I came up with this:
public static class StringHelper
{
private static readonly Dictionary<char, char> _specialChars
= new Dictionary<char, char>
{
{ 'á', 'a' },{ 'à', 'a' },{ 'â', 'a' },{ 'ã', 'a' },{ 'ä', 'a' },
{ 'é', 'e' },{ 'è', 'e' },{ 'ê', 'e' },{ 'ë', 'e' },
{ 'í', 'i' },{ 'ì', 'i' },{ 'î', 'i' },{ 'ï', 'i' },
{ 'ó', 'o' },{ 'ò', 'o' },{ 'õ', 'o' },{ 'ö', 'o' },
{ 'ú', 'u' },{ 'ù', 'u' },{ 'û', 'u' },{ 'ü', 'u' },
{ 'ç', 'c' },{ 'ñ', 'n' }
};
static StringHelper()
{
foreach (var item in _specialChars.ToList())
{
_specialChars.Add(
item.Key.ToString().ToUpper()[0],
item.Value.ToString().ToUpper()[0]);
}
}
private static readonly Regex _spaceRegex = new Regex(@"\s", RegexOptions.Compiled);
private static readonly Regex _numericRegex = new Regex(@"\s", RegexOptions.Compiled);
public static string Normalize(this string str, CharType normaliar = CharType.All)
{
if (normaliar.HasFlag(CharType.Spaces))
{
str = _spaceRegex.Replace(str, string.Empty);
}
if (normaliar.HasFlag(CharType.Special))
{
str = _specialChars.ToList()
.Aggregate(str, (ac, item) => ac.Replace(item.Key, item.Value));
}
if (normaliar.HasFlag(CharType.Numerics))
{
str = _numericRegex.Replace(str, string.Empty);
}
if (normaliar.HasFlag(CharType.UpperCase))
{
str = str.ToLower();
}
return str;
}
}
public enum CharType
{
Spaces = 1,
Special = 2,
Numerics = 4,
UpperCase = 8,
All = 15,
}
I'm not considering really all special char just Portuguese, Spanish and a few more.
As far as I could, I wrote with the better performance and organization, but this was my limit.