iOS 获取中文拼音
iOS中文转成拼音。
oc:
NSString *hanziText = @"中文转拼音"; if ([hanziText length]) { NSMutableString *ms = [[NSMutableString alloc] initWithString:hanziText]; if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) { NSLog(@"pinyin: %@", ms); } if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) { NSLog(@"pinyin: %@", ms); } }
swift:
let s = "中文转拼音" let ens = NSMutableString(string: s) as CFMutableString // 此时有声调 CFStringTransform(ens, UnsafeMutablePointer<CFRange>(), kCFStringTransformMandarinLatin, false) NSLog("\(ens)") // 去掉声调 CFStringTransform(ens, UnsafeMutablePointer<CFRange>(), kCFStringTransformStripDiacritics, false) NSLog("\(ens)")
输出如下:
注意:中英文混用转换没有问题,非中文部分不会出现任何变化。