Swift
中文转拼音(带声调)
比如:中国
-> zhōng guó
let base = "中国"
let mutableString = NSMutableString(string: base)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
print(mutableString) // zhōng guó
中文转拼音(无声调)
比如:中国
-> zhong guo
let base = "中国"
let mutableString = NSMutableString(string: base)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
CFStringTransform(mutableString, nil, kCFStringTransformStripDiacritics, false)
print(mutableString) // zhong guo
中文提取首字母
比如:中国
-> ZG
let base = "中国"
let mutableString = NSMutableString(string: base)
CFStringTransform(mutableString, nil, kCFStringTransformToLatin, false)
let pinyinArray = mutableString.components(separatedBy: " ")
let initials = pinyinArray.compactMap { String(format: "%c", $0.cString(using:.utf8)![0]) }
let firstCharJoin = initials.joined().uppercased()
print(firstCharJoin) // ZG
Objective-C
中文转拼音(带声调)
比如:中国
-> zhōng guó
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:@"中国"];
CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, NO);
NSLog(@"%@", mutableString); // zhōng guó
中文转拼音(无声调)
比如:中国
-> zhong guo
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:@"中国"];
CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, NO);
CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformStripDiacritics, false);
NSLog(@"%@", mutableString); // zhong guo
中文提取首字母
比如:中国
-> ZG
NSMutableString *mutableString = [[NSMutableString alloc] initWithString:@"中国"];
CFStringTransform((__bridge CFMutableStringRef)mutableString, NULL, kCFStringTransformToLatin, NO);
NSMutableString *firstCharJoin = [[NSMutableString alloc] init];
NSArray<NSString *> *pinyinArray = [mutableString componentsSeparatedByString:@" "];
for (NSString *pinyin in pinyinArray) {
[firstCharJoin appendFormat:@"%c", [pinyin characterAtIndex:0]];
}
NSLog(@"%@", firstCharJoin.uppercaseString); // ZG