【推薦】iOS漢字轉拼音第三方庫,ios漢字拼音第三方
PinYin4Objc是一個在git漢字轉拼音的開源庫,支援簡體和繁體中文。效率POAPinyin等其他庫要高,轉換庫也完整下面簡單介紹
實現原理
使用unicode_to_hanyu_pinyin.txt儲存漢字編碼相對應的拼音,以字典載入到記憶體中
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];
當我們輸入漢字後,得到該漢字的編碼。下面圖為例。當我們點擊OK按鈕後
NSString *mainPinyinStrOfChar = [PinyinHelper getFirstHanyuPinyinStringWithChar:[str characterAtIndex:i] withHanyuPinyinOutputFormat:outputFormat];通過迴圈來產生漢字編碼
從字典中查詢key為“8F6C”的值為
取數組第一個就為拼音...
使用
1.下載庫
2.引入標頭檔 #import "PinYin4Objc.h"
3.建立拼音字元格式設定
HanyuPinyinOutputFormat *outputFormat=[[HanyuPinyinOutputFormat alloc] init];
格式包含ToneType,CharType,CaseType
typedef enum { ToneTypeWithToneNumber,//有音調數字,如PIN1 ToneTypeWithoutTone,//無音調 ToneTypeWithToneMark}ToneType;
typedef enum { CaseTypeUppercase,//拼音大小 CaseTypeLowercase// 拼音小寫}CaseType;
typedef enum { VCharTypeWithUAndColon, VCharTypeWithV, VCharTypeWithUUnicode}VCharType;
4.設定格式
[outputFormat setToneType:ToneTypeWithoutTone];
[outputFormat setVCharType:VCharTypeWithV];
[outputFormat setCaseType:CaseTypeLowercase];
5.調用toHanyuPinyinStringWithNSString:withHanyuPinyinOutputFormat:withNSString:outputBlock進行轉換
[PinyinHelper toHanyuPinyinStringWithNSString:sourceText withHanyuPinyinOutputFormat:outputFormat withNSString:@" " outputBlock:^(NSString *pinYin) { _outputTv.text=pinYin; }];