0

For searching I need to remove all occurrences of characters containing a circumflex, a caret, or a apostrophe like á with a "normal" a. Is there a better way than manually replacing all known occurrences like this?

    _string = [_string stringByReplacingOccurrencesOfString:@"é" withString:@"e"];
    _string = [_string stringByReplacingOccurrencesOfString:@"è" withString:@"e"];
    _string = [_string stringByReplacingOccurrencesOfString:@"ê" withString:@"e"];
    _string = [_string stringByReplacingOccurrencesOfString:@"á" withString:@"a"];
    _string = [_string stringByReplacingOccurrencesOfString:@"à" withString:@"a"];
    _string = [_string stringByReplacingOccurrencesOfString:@"â" withString:@"a"];
    _string = [_string stringByReplacingOccurrencesOfString:@"ó" withString:@"o"];
    _string = [_string stringByReplacingOccurrencesOfString:@"ò" withString:@"o"];
    _string = [_string stringByReplacingOccurrencesOfString:@"ô" withString:@"o"];
    _string = [_string stringByReplacingOccurrencesOfString:@"ú" withString:@"u"];
    _string = [_string stringByReplacingOccurrencesOfString:@"ù" withString:@"u"];
    _string = [_string stringByReplacingOccurrencesOfString:@"û" withString:@"u"];
    _string = [_string stringByReplacingOccurrencesOfString:@"í" withString:@"i"];
    _string = [_string stringByReplacingOccurrencesOfString:@"ì" withString:@"i"];
    _string = [_string stringByReplacingOccurrencesOfString:@"î" withString:@"i"];

This is an example code, so I know that a loop is a improvement for this solution. But this is not maintainable at all.

Thomas Kekeisen
  • 4,355
  • 4
  • 35
  • 54

1 Answers1

2

How are you doing the searching? If you're comparing the strings in your own code, you can use -[NSString compare:options:] with options like NSDiacriticInsensitiveSearch and NSWidthInsensitiveSearch as well as the more well-known NSCaseInsensitiveSearch. If you omit NSLiteralSearch, then decomposed sequences will match their precomposed counterparts, which is usually what you want.

If you're using a predicate, you can apply the [d] modifier to the comparison operator, like CONTAINS[d].

If you really want to transform the string rather than just changing how you compare, you want the -stringByFoldingWithOptions:locale: method:

_string = [_string precomposedStringWithCanonicalMapping];
_string = [_string stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:nil];
Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • Thanks works a lot faster than my solution. But to be complete, the solution from here works, too: http://stackoverflow.com/questions/7965301/remove-all-accents-by-string – Thomas Kekeisen Jul 09 '14 at 12:25