How do i replace accents (german) in .NET

subha picture subha · Aug 13, 2009 · Viewed 18.6k times · Source

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#

Answer

dahlbyk picture dahlbyk · Aug 13, 2009

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();