开发者

NSString - how to go from "ÁlgeBra" to "Algebra"

D开发者_StackOverflowoes anyone knows hoe to get a NSString like "ÁlgeBra" to "Algebra", without the accent, and capitalize only the first letter?

Thanks,

RL


dreamlax has already mentioned the capitalizedString method. Instead of doing a lossy conversion to and from NSData to remove the accented characters, however, I think it is more elegant to use the stringByFoldingWithOptions:locale: method.

NSString *accentedString = @"ÁlgeBra";
NSString *unaccentedString = [accentedString stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
NSString *capitalizedString = [unaccentedString capitalizedString];

Depending on the nature of the strings you want to convert, you might want to set a fixed locale (e.g. English) instead of using the user's current locale. That way, you can be sure to get the same results on every machine.


NSString has a method called capitalizedString:

Return Value

A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.

NSString *str = @"AlgeBra";
NSString *other = [str capitalizedString];

NSLog (@"Old: %@, New: %@", str, other);

Edit:

Just saw that you would like to remove accents as well. You can go through a series of steps:

// original string
NSString *str = @"ÁlgeBra";

// convert to a data object, using a lossy conversion to ASCII
NSData *asciiEncoded = [str dataUsingEncoding:NSASCIIStringEncoding
                         allowLossyConversion:YES];

// take the data object and recreate a string using the lossy conversion
NSString *other = [[NSString alloc] initWithData:asciiEncoded
                                        encoding:NSASCIIStringEncoding];
// relinquish ownership
[other autorelease];

// create final capitalized string
NSString *final = [other capitalizedString];

The documentation for dataUsingEncoding:allowLossyConversion: explicitly says that the letter ‘Á’ will convert to ‘A’ when converting to ASCII.


Here's a step by step example of how to do it. There's room for improvement, but you get the basic idea......

NSString *input = @"ÁlgeBra";
NSString *correctCase = [NSString stringWithFormat:@"%@%@",
                           [[input substringToIndex:1] uppercaseString],
                           [[input substringFromIndex:1] lowercaseString]];

NSString *result = [[[NSString alloc] initWithData:[correctCase dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES] encoding:NSASCIIStringEncoding] autorelease];

NSLog( @"%@", result );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜