-2

How can I replace all accented characters in a string with standard ASCII characters?

Examples

from: cartões
to:   cartoes
from: notificações
to:   notificacoes
Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
Paulo Rodrigues
  • 397
  • 4
  • 20
  • Why do you need this? If your intent is to search a string what you need is `localizedStandardContains` which is case and diacritic insensitive as well as locale-aware – Leo Dabus Sep 22 '22 at 02:22

1 Answers1

1

Swift has built in support for stripping diacritics/annotations from strings. This is primarily to support easy searching and comparisons but will solve your problem too. The API is

func folding( options: String.CompareOptions = [],
    locale: Locale?) -> String

If you will be using it regularly, the easiest way would be to create an extension on String with the required parameters preset:

extension String {
  func cleaned() -> Self {
    return self.folding(options: .diacriticInsensitive, locale: .current)
  }
}

which would let you do "notificações".cleaned() to return notificacoes

flanker
  • 3,840
  • 1
  • 12
  • 20
  • `Swift has built in support` This is not true. There is no "built-in" method AFAIK. `folding` as well as `applyingTransform` methods require you to import `Foundation`. – Leo Dabus Sep 22 '22 at 02:17
  • 1
    Slightly pedantic, but technically accurate :) – flanker Sep 22 '22 at 08:26