在iOS开发中,有时我们需要获取中文汉字的首字母,此时可以使用以下方法。
思路:
1、转成了可变字符串
2、先转换为带声调的拼音
3、再转换为不带声调的拼音
4、将拼音的首字母转化为大写
5、遍历最新拼音字符串,获取首字母
//获取汉字的首字母
- (NSString *)firstCharactor:(NSString *)aString
{
NSMutableString *str = [NSMutableString stringWithString:aString];
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
NSString *pinYin = [str capitalizedString];
NSString *firatCharactors = [NSMutableString string];
for (int i = 0; i < pinYin.length; i++) {
if ([pinYin characterAtIndex:i] >= 'A' && [pinYin characterAtIndex:i] <= 'Z') {
firatCharactors = [firatCharactors stringByAppendingString:[NSString stringWithFormat:@"%C",[pinYin characterAtIndex:i]]];
}
}
return firatCharactors;
}
网友评论