NSString - Convert to pure alphabet only (i.e. remove accents+punctuation)

前端 未结 13 1392
暖寄归人
暖寄归人 2020-12-02 15:49

I\'m trying to compare names without any punctuation, spaces, accents etc. At the moment I am doing the following:

-(NSString*) prepareString:(NSString*)a {
         


        
相关标签:
13条回答
  • 2020-12-02 16:40

    These answers didn't work as expected for me. Specifically, decomposedStringWithCanonicalMapping didn't strip accents/umlauts as I'd expected.

    Here's a variation on what I used that answers the brief:

    // replace accents, umlauts etc with equivalent letter i.e 'é' becomes 'e'.
    // Always use en_GB (or a locale without the characters you wish to strip) as locale, no matter which language we're taking as input
    NSString *processedString = [string stringByFoldingWithOptions: NSDiacriticInsensitiveSearch locale: [NSLocale localeWithLocaleIdentifier: @"en_GB"]];
    // remove non-letters
    processedString = [[processedString componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];
    // trim whitespace
    processedString = [processedString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
    return processedString;
    
    0 讨论(0)
提交回复
热议问题