字符串数组排序/分组

//获取字符串(或者汉字)的首字母

-(NSString*)firstCharacterWithString:(NSString *)string

{

    NSMutableString *str = [NSMutableString stringWithString:string];

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);

    NSString *pingyin = [str capitalizedString];

    return [pingyin substringFromIndex:1];

}

//将字符串属猪按照元素首字母进行排序分组

-(NSDictionary *)dictonaryOrderByCharaterWithOriginalArray:(NSArray *)array

{

    if (array.count == 0) {

        return nil;

    }

    for (id obj in array) {

        if (![obj isKindOfClass:[NSString class]]) {

            return nil;

        }

    }

    UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation currentCollation];

    NSMutableArray *objects =[NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count];

    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {

        NSMutableArray *array = [NSMutableArray array];

        [objects addObject:array];

        

    }

    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];

    

    //按字母顺序分组

    NSInteger lastIndex = -1;

    for (int i = 0; i < array.count; i ++) {

        NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)];

        [[objects objectAtIndex:index]addObject:array[i]];

        lastIndex = index;

    }

    

    //去掉空数组

    for (int i = 0; i<objects.count; i++) {

        NSMutableArray *obj = objects[i];

        if (obj.count  == 0) {

            [objects removeObject:obj];

        }

    }

    

    //获取索引字母

    for (NSMutableArray *obj in objects) {

        NSString *str = obj[0];

        NSString *key = [self firstCharacterWithString:str];

        [keys addObject:key];

    }

    NSMutableDictionary *dic = [NSMutableDictionary dictionary];

    [dic setObject:objects forKey:keys];

    return dic;

}

 

转载于:https://www.cnblogs.com/PJXWang/p/5614832.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值