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