获取拼音首字母(等)

//获取拼音首字母(传入汉字字符串, 返回大写拼音首字母)

-(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];

    //获取并返回首字母

    return [pinYin substringToIndex:1];

}

//  判断是否以字母开头

- (BOOL)isEnglishFirst:(NSString*)str {

    NSString*regular =@"^[A-Za-z]";

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regular];


    if([predicate evaluateWithObject:str] ==YES){

        return YES;

    }else{

        return NO;

    }

}

//  判断是否以汉字开头

- (BOOL)isChineseFirst:(NSString*)str {

    int utfCode =0;

    void *buffer = &utfCode;

    NSRange range = NSMakeRange(0, 1);

    BOOL b = [str getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];

    if(b && (utfCode >=0x4e00 && utfCode <= 0x9fa5)){

        return YES;

    }else{

        return NO;

    }

}

你可能感兴趣的:(获取拼音首字母(等))