NSString - how to go from “ÁlgeBra” to “Algebra”

让人想犯罪 __ 提交于 2019-11-27 22:45:59

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.

Ole Begemann

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.

zrzka

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 );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!