8.25 将汉字转化为拼音的NSString类目category
//
// NSString+Characters.h
#import <Foundation/Foundation.h>
@interface NSString (Characters)
//将汉字转换为拼音(无音标)
- (NSString *)pinyinOfString;
//汉字转换为拼音后,返回大写的首字母
- (NSString *)firstCharacterOfString;
@end
//
// NSString+Characters.m
// AddressBook
#import "NSString+Characters.h"
@implementation NSString (Characters)
//将汉字转换为拼音
- (NSString *)pinyinOfString
{
NSMutableString * string = [[[NSMutableString alloc] initWithString:self ] autorelease];
CFRange range = CFRangeMake(0, 1);
// 汉字转换为拼音,并去除音调
if ( ! CFStringTransform((__bridge CFMutableStringRef) string, &range, kCFStringTransformMandarinLatin, NO) ||
! CFStringTransform((__bridge CFMutableStringRef) string, &range, kCFStringTransformStripDiacritics, NO)) {
return @"";
}
return string;
}
//汉字转换为拼音后,返回大写的首字母
- (NSString *)firstCharacterOfString
{
NSMutableString * first = [[[NSMutableString alloc] initWithString:[self substringWithRange:NSMakeRange(0, 1)]] autorelease];
CFRange range = CFRangeMake(0, 1);
// 汉字转换为拼音,并去除音调
if ( ! CFStringTransform((__bridge CFMutableStringRef) first, &range, kCFStringTransformMandarinLatin, NO) ||
! CFStringTransform((__bridge CFMutableStringRef) first, &range, kCFStringTransformStripDiacritics, NO)) {
return @"";
}
NSString * result;
result = [first substringWithRange:NSMakeRange(0, 1)];
return result.uppercaseString;
}