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