[Recommended] third-party library for converting iOS Chinese characters to pinyin, and third-party library for ios Chinese characters to PinYin
PinYin4Objc is an open-source git Chinese character-to-pinyin library that supports simplified and traditional Chinese characters. Efficiency other libraries such as POAPinyin should be high. The conversion library is also described below.
Implementation Principle
Use unicode_to_hanyu_pinyin.txt to store the pinyin corresponding to the Chinese character encoding and load it into the memory in a dictionary.
NSString *resourceName =[[NSBundle mainBundle] pathForResource:@"unicode_to_hanyu_pinyin" ofType:@"txt"]; NSString *dictionaryText=[NSString stringWithContentsOfFile:resourceName encoding:NSUTF8StringEncoding error:nil]; NSArray *lines = [dictionaryText componentsSeparatedByString:@"\r\n"]; __block NSMutableDictionary *tempMap=[[NSMutableDictionary alloc] init]; @autoreleasepool { [lines enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { NSArray *lineComponents=[obj componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; [tempMap setObject:lineComponents[1] forKey:lineComponents[0]]; }]; } self->_unicodeToHanyuPinyinTable=tempMap; [self cacheObjec:self->_unicodeToHanyuPinyinTable forKey:kCacheKeyForUnicode2Pinyin];
After entering a Chinese character, we can get the encoding of the Chinese character. The following figure is used as an example. When we click OK
NSString * mainPinyinStrOfChar = [PinyinHelper getFirstHanyuPinyinStringWithChar: [str characterAtIndex: I] withHanyuPinyinOutputFormat: outputFormat]; generate Chinese characters in a loop
The value of "8F6C" in the dictionary is
The first one in the array is pinyin...
Use
1. Download the library
2. Introduce the header file # import "PinYin4Objc. h"
3. Create a pinyin character format
HanyuPinyinOutputFormat * outputFormat = [[HanyuPinyinOutputFormat alloc] init];
The format includes ToneType, CharType, and CaseType.
Typedef enum {ToneTypeWithToneNumber, // has a tone number, such as PIN1 ToneTypeWithoutTone, // has no tone ToneTypeWithToneMark} ToneType;
Typedef enum {CaseTypeUppercase, // pinyin size CaseTypeLowercase // pinyin lowercase} CaseType;
typedef enum { VCharTypeWithUAndColon, VCharTypeWithV, VCharTypeWithUUnicode}VCharType;
4. Set the format
[OutputFormat setToneType: ToneTypeWithoutTone];
[OutputFormat setVCharType: VCharTypeWithV];
[OutputFormat setCaseType: CaseTypeLowercase];
5. Call toHanyuPinyinStringWithNSString: withHanyuPinyinOutputFormat: withNSString: outputBlock for conversion.
[PinyinHelper toHanyuPinyinStringWithNSString:sourceText withHanyuPinyinOutputFormat:outputFormat withNSString:@" " outputBlock:^(NSString *pinYin) { _outputTv.text=pinYin; }];