Pinyin of iOS Chinese characters

  • 2020-06-23 02:00:39
  • OfStack

Without further ado, I will post the key code directly to you.

The specific code is as follows:


#import <Foundation/Foundation.h>
@interface NSString (Utils)
/**
*  Pinyin of Chinese characters 
*
* @return  pinyin 
*/
- (NSString *)pinyin;
@end
#import "NSString+Utils.h"
@implementation NSString (Utils)
// Pinyin of Chinese characters 
- (NSString *)pinyin{
NSMutableString *str = [self mutableCopy];
CFStringTransform(( CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
return [str stringByReplacingOccurrencesOfString:@" " withString:@""];
}
@end

Next, iOS turns Chinese characters into pinyin

During the development of ios, I often encountered the situation that making an address book required converting Chinese characters into pinyin. The following is how I converted Chinese characters into pinyin


+ (NSString *)transform:(NSString *)chinese
{
  NSMutableString *pinyin = [chinese mutableCopy];
  CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
  CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
  NSLog(@"%@", pinyin);
  return [pinyin uppercaseString];
}

kCFStringTransformMandarinLatin method is used to convert pinyin with phonetic symbols. If the phonetic symbol needs to be removed, the kCFStringTransformStripCombiningMarks method can be used again.


Related articles: