码迷,mamicode.com
首页 > 编程语言 > 详细

字符串数组排序/分组

时间:2016-06-24 17:29:17      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

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

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

}

 

字符串数组排序/分组

标签:

原文地址:http://www.cnblogs.com/PJXWang/p/5614832.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!