June 14, 2009 | In: snippet

Replacing special Chars in a String c#

I have been working on a c# french desktop application. Unfortunately iTextSharp, which is an open source java library for PDF generation written entirely in C# for the .NET platform, do not allow to print special chars (é, è, ç …etc.) properly.

Happily, I found this very useful piece of code in the Internet and I want to share it with you:

C#
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/// <summary>
/// Delete all Accents
/// </summary>
/// <param name="txt">Source String with accents and special Char</param>
/// <returns>Source String without accents and special Char</returns>
private static string DeleteAccentAndSpecialsChar(string OriginalText)
{
string strTemp = OriginalText;
// Regex creation
Regex regA = new Regex("[ã|à|â|ä|á|å]");
Regex regAA = new Regex("[Ã|À|Â|Ä|Á|Å]");
Regex regE = new Regex("[é|è|ê|ë]");
Regex regEE = new Regex("[É|È|Ê|Ë]");
Regex regI = new Regex("[í|ì|î|ï]");
Regex regII = new Regex("[Í|Ì|Î|Ï]");
Regex regO = new Regex("[õ|ò|ó|ô|ö]");
Regex regOO = new Regex("[Õ|Ó|Ò|Ô|Ö]");
Regex regU = new Regex("[ù|ú|û|ü|µ]");
Regex regUU = new Regex("[Ü|Ú|Ù|Û]");
Regex regY = new Regex("[ý|ÿ]");
Regex regYY = new Regex("[Ý]");
Regex regAE = new Regex("[æ]");
Regex regAEAE = new Regex("[Æ]");
Regex regOE = new Regex("[œ]");
Regex regOEOE = new Regex("[Œ]");
Regex regC = new Regex("[ç]");
Regex regCC = new Regex("[Ç]");
Regex regDD = new Regex("[Ð]");
Regex regN = new Regex("[ñ]");
Regex regNN = new Regex("[Ñ]");
Regex regS = new Regex("[š]");
Regex regSS = new Regex("[Š]");
strTemp = regA.Replace(strTemp, "a");
strTemp = regAA.Replace(strTemp, "A");
strTemp = regE.Replace(strTemp, "e");
strTemp = regEE.Replace(strTemp, "E");
strTemp = regI.Replace(strTemp, "i");
strTemp = regII.Replace(strTemp, "I");
strTemp = regO.Replace(strTemp, "o");
strTemp = regOO.Replace(strTemp, "O");
strTemp = regU.Replace(strTemp, "u");
strTemp = regUU.Replace(strTemp, "U");
strTemp = regY.Replace(strTemp, "y");
strTemp = regYY.Replace(strTemp, "Y");
strTemp = regAE.Replace(strTemp, "ae");
strTemp = regAEAE.Replace(strTemp, "AE");
strTemp = regOE.Replace(strTemp, "oe");
strTemp = regOEOE.Replace(strTemp, "OE");
strTemp = regC.Replace(strTemp, "c");
strTemp = regCC.Replace(strTemp, "C");
strTemp = regDD.Replace(strTemp, "D");
strTemp = regN.Replace(strTemp, "n");
strTemp = regNN.Replace(strTemp, "N");
strTemp = regS.Replace(strTemp, "s");
strTemp = regSS.Replace(strTemp, "S");
return strTemp;
return strTemp;
}

Source : http://www.codyx.org/snippet_modifie-caracteres-speciaux_154.aspx
ps : Don’t forget to import RegularExpressions in your namespace.

C#
1
using System.Text.RegularExpressions;

Comment Form

Categories