Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i replace accents (german) in .NET

I need to replace accents in the string to their english equivalents

for example

ä = ae

ö = oe

Ö = Oe

ü = ue

I know to strip of them from string but i was unaware about replacement.

Please let me know if you have some suggestions. I am coding in C#

like image 923
subha Avatar asked Aug 13 '09 12:08

subha


2 Answers

If you need to use this on larger strings, multiple calls to Replace() can get inefficient pretty quickly. You may be better off rebuilding your string character-by-character:

var map = new Dictionary<char, string>() {
  { 'ä', "ae" },
  { 'ö', "oe" },
  { 'ü', "ue" },
  { 'Ä', "Ae" },
  { 'Ö', "Oe" },
  { 'Ü', "Ue" },
  { 'ß', "ss" }
};

var res = germanText.Aggregate(
              new StringBuilder(),
              (sb, c) => map.TryGetValue(c, out var r) ? sb.Append(r) : sb.Append(c)
              ).ToString();
like image 83
dahlbyk Avatar answered Oct 12 '22 18:10

dahlbyk


Do just want a mapping of german umlauts to the two-letter (non-umlaut) variant? Here you go; untested, but it handles all german umlauts.

String replaceGermanUmlauts( String s ) {
    String t = s;
    t = t.Replace( "ä", "ae" );
    t = t.Replace( "ö", "oe" );
    t = t.Replace( "ü", "ue" );
    t = t.Replace( "Ä", "Ae" );
    t = t.Replace( "Ö", "Oe" );
    t = t.Replace( "Ü", "Ue" );
    t = t.Replace( "ß", "ss" );
    return t;
}
like image 29
Frerich Raabe Avatar answered Oct 12 '22 18:10

Frerich Raabe