Removendo a acentuação e os caracteres especiais de uma String
Posted by Luiz Picanço | Posted in .Net, C# | Posted on 28-05-2010
Tags: .Net, algoritmo, C#
2
Estava precisando remover a acentuação e os caracteres especiais do nome de um arquivo. Para isso, desenvolvi um extension method para a classe String.
Exemplo:
String de entrada:
Adobe Acrobat – Pacy-Paraná_05.12_áèïôúã+.pdf
String de retorno:
AdobeAcrobatPacyParana_05.12_aeioua.pdf
Desenvolvi o método utilizando uma HashTable e expressão regular. Caso você tenha alguma sugestão de melhoria, poste aí nos comentários.
Extension method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public static String RemoveSpecialCharacters(this String self) { var normalizedString = self; // Prepara a tabela de símbolos. var symbolTable = new Dictionary<char, char[]>(); symbolTable.Add('a', new char[] {'à', 'á', 'ä', 'â', 'ã'}); symbolTable.Add('c', new char[] { 'ç' }); symbolTable.Add('e', new char[] { 'è', 'é', 'ë', 'ê' }); symbolTable.Add('i', new char[] { 'ì', 'í', 'ï', 'î' }); symbolTable.Add('o', new char[] { 'ò', 'ó', 'ö', 'ô', 'õ' }); symbolTable.Add('u', new char[] { 'ù', 'ú', 'ü', 'û' }); // Substitui os símbolos. foreach (var key in symbolTable.Keys) { foreach (var symbol in symbolTable[key]) { normalizedString = normalizedString.Replace(symbol, key); } } // Remove os outros caracteres especiais. normalizedString = Regex.Replace(normalizedString, "[^0-9a-zA-Z._]+?", ""); return normalizedString; } |

