Featured Post

Microsoft Surface

Hoje, à 00:01, a Microsoft revelou um computador em formato de mesa, o que representa um grande passo em direção à visão do co-fundador Bill Gates sobre um futuro no qual o mouse e o teclado serão substituídos por meios mais naturais de interação como a voz, uma caneta ou o tato. O nome do...

Read More

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: , ,

2,054

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;
}

Comments (2,054)

Recent Blogroll Additions…

I saw this really good post today….

2011…

I really appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You’ve made my day! Thank you again…

Sources…

[...]check below, are some totally unrelated websites to ours, however, they are most trustworthy sources that we use[...]……

Kamasz…

[...]the time to read or visit the content or sites we have linked to below the[...]…

Write a comment

You must be logged in to post a comment.