.h文件
#import <Foundation/Foundation.h>
@interface ChineseTool : NSObject
/**
* 汉字转拼音
*
* @param chinese 要转换的汉字
* @param stripDiacritics 是否需要音标
*
* @return 拼音
*/
+ (NSString *)pinyinForChinese:(NSString *)chinese stripDiacritics:(BOOL)stripDiacritics;
/**
* 对汉字数组进行排序
*
* @param chineseArr 汉字数组
*
* @return 排好序的数组
*/
+ (NSArray *)sortForChineseArr:(NSArray *)chineseArr;
@end
.m文件
#import "ChineseTool.h"
@implementation ChineseTool
+ (NSString *)pinyinForChinese:(NSString *)chinese stripDiacritics:(BOOL)stripDiacritics
{
if ([chinese length]) {
NSMutableString *ms = [[NSMutableString alloc] initWithString:chinese];
if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformMandarinLatin, NO)) {
if (stripDiacritics) {
if (CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO)) {
return ms;
}
} else {
return ms;
}
}
}
return nil;
}
+ (NSArray *)sortForChineseArr:(NSArray *)chineseArr
{
NSMutableArray *pinyinArr = [NSMutableArray arrayWithCapacity:0];
for (NSString *str in chineseArr) {
NSString *pinyin = [[self pinyinForChinese:str stripDiacritics:YES] stringByReplacingOccurrencesOfString:@" " withString:@""];
[pinyinArr addObject:pinyin];
}
NSDictionary *dict = [NSDictionary dictionaryWithObjects:chineseArr forKeys:pinyinArr];
NSArray *sortPinyinArr = [pinyinArr sortedArrayUsingSelector:@selector(compare:)];
NSArray *chineseSortArr = [dict objectsForKeys:sortPinyinArr notFoundMarker:[NSNull null]];
return chineseSortArr;
}