How do i replace accents (german) in .NET

前端 未结 5 2157
有刺的猬
有刺的猬 2020-12-03 17:36

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

for example

ä = ae

ö = oe

Ö = Oe

ü = ue

I know to strip

5条回答
  •  执念已碎
    2020-12-03 18:13

    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() {
      { 'ä', "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();
    

提交回复
热议问题