iphone - 将数组排序到字典中

标签 iphone ios arrays sorting nsdictionary

我有许多字符串的数组。 我不想将它们分类到字典中,因此所有以相同字母开头的字符串都进入一个数组,然后该数组成为键的值;键将是其值数组中所有单词的开头字母。

例子

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

我该怎么做? 非常感谢!

最佳答案

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

关于iphone - 将数组排序到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6973597/

相关文章:

iphone - iOS 应用程序在临时安装后设备重新启动之前不会运行

iphone - 硬件加速 h.264 解码到 iOS 中的纹理、覆盖或类似内容

iphone - 子类化的 UIView 没有设置标签

javascript - 是否可以像在java中一样在javascript中初始化二维数组?

Javascript:总和或所有数字在for循环中不起作用

iphone - 如何在 Objective C 中阻止来电、短信和电子邮件

ios - UICollectionView cellForItemAtIndexPath 在滚动时一遍又一遍地调用

iphone - 设置自定义 UINavigationBar

ios - 在后台通过 iCloud 同步本地通知

html - 从 HTML 文件中显示格式数组