zoukankan      html  css  js  c++  java
  • 字符串数组排序/分组

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

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

    }

  • 相关阅读:
    python isinstance函数 判断元素是否是字符串、int型、float型
    Day04 list(列表)
    Day 05 Dict字典
    Python的简介
    DAY7 字符编码和文件操作
    DAY6 元组、字典与集合
    DAY5 基本数据类型及内置方法
    DAY4 if、while和for
    DAY3 数据类型与运算符
    DAY2 初识python
  • 原文地址:https://www.cnblogs.com/PJXWang/p/5614832.html
Copyright © 2011-2022 走看看