使用方法:
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;
}