使用方法:
NSMutableString *source = [sourceString mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
return source;
在这个方法中kCFStringTransformMandarinLatin讲汉字转为拼音,再调用kCFStringTransformStripDiacritics去掉声调,
我在这里犯下的错误是没有把这两行都写上,而是只写一行,那么就早成只有第一行,那就只转出带声调的拼音,只写出第二行只会返回汉字,
后来我的领导对方法进行了优化,因为部分字会被转成错误的拼音所以完整方法是这样并且可以支持排序,
- (NSString *) phonetic:(NSString*)sourceString {
if ([sourceString isEqualToString:@""]) {
return sourceString;
}
NSMutableString *source = [sourceString mutableCopy];
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
if ([[(NSString *)sourceString substringToIndex:1] compare:@"长"] ==NSOrderedSame)
{
[source replaceCharactersInRange:NSMakeRange(0, 5)withString:@"chang"];
}
if ([[(NSString *)sourceString substringToIndex:1] compare:@"沈"] ==NSOrderedSame)
{
[source replaceCharactersInRange:NSMakeRange(0, 4)withString:@"shen"];
}
if ([[(NSString *)sourceString substringToIndex:1] compare:@"厦"] ==NSOrderedSame)
{
[source replaceCharactersInRange:NSMakeRange(0, 3)withString:@"xia"];
}
if ([[(NSString *)sourceString substringToIndex:1] compare:@"地"] ==NSOrderedSame)
{
[source replaceCharactersInRange:NSMakeRange(0, 3)withString:@"di"];
}
if ([[(NSString *)sourceString substringToIndex:1] compare:@"重"] ==NSOrderedSame)
{
[source replaceCharactersInRange:NSMakeRange(0, 5) withString:@"chong"];
}
return source;
}
使用CFStringTransform进行汉字转拼音(可去掉声调),布布扣,bubuko.com
使用CFStringTransform进行汉字转拼音(可去掉声调)
原文地址:http://www.cnblogs.com/tuhaoYY/p/3850799.html