排序数组字典 [英] Sort array into dictionary

查看:255
本文介绍了排序数组字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多字符串数组。
我wan't将它们整理成一本字典,所以所有开始同一封信去到一个数组,然后数组成为一个关键的字符串值;关键是与其中的所有词的价值的数组开头字母。

示例

 键=A>>值=数组=苹果,动物,字母,ABC ......
答案=B>>值=数组=蝙蝠,球,香蕉......

我怎样才能做到这一点?
非常感谢事先!


解决方案

 的NSArray *名单= [NSArray的arrayWithObjects:@苹果,动物,蝙蝠,球,零]
*的NSMutableDictionary字典=的NSMutableDictionary字典]
对于(的NSString *单词){
    的NSString * firstLetter = [[字substringToIndex:1] uppercaseString];
    NSMutableArray里* letterList = [字典objectForKey:firstLetter];
    如果(!letterList){
        letterList = [NSMutableArray的阵列]
        [字典的setObject:letterList forKey:firstLetter];
    }
    [letterList ADDOBJECT:字]。
}
的NSLog(@%@,字典);

I have and array of many strings. I wan't to sort them into a dictionary, so all strings starting the same letter go into one array and then the array becomes the value for a key; the key would be the letter with which all the words in it's value's array begin.

Example

Key = "A" >> Value = "array = apple, animal, alphabet, abc ..."
Key = "B" >> Value = "array = bat, ball, banana ..."

How can I do that? Thanks a lot in advance!

解决方案

NSArray *list = [NSArray arrayWithObjects:@"apple, animal, bat, ball", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in list) {
    NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
    NSMutableArray *letterList = [dict objectForKey:firstLetter];
    if (!letterList) {
        letterList = [NSMutableArray array];
        [dict setObject:letterList forKey:firstLetter];
    }
    [letterList addObject:word];
}
NSLog(@"%@", dict);

这篇关于排序数组字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆