【iOS开发】字符串汉字转拼音

时间:2023-01-04 17:34:20

汉字转拼音方法:


// 汉字转拼音
- (NSString *)transformChineseToPinyin:(NSString *)chinese{
//将NSString装换成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];

//将汉字转换为拼音(带音标)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);

//去掉拼音的音标
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);

//返回最近结果
return pinyin;

}

完整代码:

- (void)viewDidLoad
{
[super viewDidLoad];

NSString *string_before = @"江一燕";
NSString *string_after = @"";
string_after = [self transformChineseToPinyin:string_before];

NSLog(@"转换前-----%@ 转换后-----%@",string_before,string_after);
}

// 汉字转拼音
- (NSString *)transformChineseToPinyin:(NSString *)chinese{
//将NSString装换成NSMutableString
NSMutableString *pinyin = [chinese mutableCopy];

//将汉字转换为拼音(带音标)
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);

//去掉拼音的音标
CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);

//返回最近结果
return pinyin;

}

结果Log:

【iOS开发】字符串汉字转拼音

Demo地址:Demo_ChineseToPinYin