获取汉字首字母

时间:2022-01-27 08:02:17
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSString *currentText = @"原因很明显了,微信首要任务是换着法子从用户口袋里捞钱,不会想让用户仅仅把他当做聊天工具,让用户进入微信多看广告才是微信想要做的(但微信吃相这么难看";
    [currentText enumerateSubstringsInRange:NSMakeRange(0, currentText.length) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop)
    {
        printf("%s",[[ViewController getFirstLetter:substring] UTF8String]);
    }];
}

+(NSString *)getFirstLetter:(NSString *) strInput
{
    
    if ([strInput length])
    {
        NSMutableString *ms = [[NSMutableString alloc] initWithString:strInput];
        // 1. kCFStringTransformMandarinLatin 表示中文转拉丁字母,NULL 表示转换范围为整个字符串
        CFStringTransform((__bridge CFMutableStringRef)ms, NULL, kCFStringTransformMandarinLatin, NO);
        // 2. kCFStringTransformStripDiacritics,去掉音调
        CFStringTransform((__bridge CFMutableStringRef)ms, 0, kCFStringTransformStripDiacritics, NO);
        // 3. 转换结果是按将个汉字的拼音以空格分隔的,我们将每个汉字的拼音按空格切开放到数组中
        NSArray *pyArray = [ms componentsSeparatedByString:@" "];
        if(pyArray && pyArray.count > 0)
        {
            ms = [[NSMutableString alloc] init];
            // 4. 只取每个汉字的首字母
            for (NSString *strTemp in pyArray)
            {
                [ms appendString:[strTemp substringToIndex:1]];
            }
            return [ms uppercaseString];
        }
        ms = nil;
    }
    return nil;
}