排序数组字典

编程入门 行业动态 更新时间:2024-10-17 23:34:10
本文介绍了排序数组字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有许多字符串数组。我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);

更多推荐

排序数组字典

本文发布于:2023-11-30 09:28:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649500.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!