Search code examples
iphoneiosuppercase

Uppercase first letter in NSString


How can I uppercase the fisrt letter of a NSString, and removing any accents ?

For instance, Àlter, Alter, alter should become Alter.

But, /lter, )lter, :lter should remains the same, as the first character is not a letter.


Solution

  • Since you want to remove diacritic marks, you could use this method in combination with the common string manipulating methods, like this:

    /* create a locale where diacritic marks are not considered important, e.g. US English */
    NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en-US"] autorelease];
    
    NSString *input = @"Àlter";
    
    /* get first char */
    NSString *firstChar = [input substringToIndex:1];
    
    /* remove any diacritic mark */
    NSString *folded = [firstChar stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:locale];
    
    /* create the new string */
    NSString *result = [[folded uppercaseString] stringByAppendingString:[input substringFromIndex:1]];