Sunday, May 19, 2013

NSString stringByFoldingWithOptions example ios


stringByFoldingWithOptions: locale:

Returns a string with the given character folding options applied.
- (NSString *)stringByFoldingWithOptions:(NSStringCompareOptions)options locale:(NSLocale *)locale
Parameters
options
A mask of compare flags with a suffix InsensitiveSearch.
locale
The locale to use for the folding. The locale affects the folding logic. For example, for the Turkish locale, case-insensitive compare matches “I” to “ı” (Unicode code point U+0131, Latin Small Dotless I), not the normal “i” character.
Return Value of [NSString stringByFoldingWithOptions]
A string with the character folding options applied.
Discussion
Character folding operations remove distinctions between characters. For example, case folding may replace uppercase letters with their lowercase equivalents.
Example of [NSString stringByFoldingWithOptions]
NSString *accentedString = @"ÁlgeBra";
NSString *unaccentedString = [accentedString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
NSString *capitalizedString = [unaccentedString capitalizedString];
Example of [NSString stringByFoldingWithOptions]
/* 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]];
Example of [NSString stringByFoldingWithOptions]
NSString *fold1 = [str1 stringByFoldingWithOptions:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch | NSWidthInsensitiveSearch locale:[NSLocale currentLocale]];
NSString *fold2 = [str2 stringByFoldingWithOptions:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch | NSWidthInsensitiveSearch locale:[NSLocale currentLocale]];
NSRange range = [fold1 rangeOfString:fold2]; // or other string comparisons