我有这样的数组数据。
animals = @[@"Bear", @"Black Swan", @"Buffalo", @"Camel", @"Cockatoo", @"Dog", @"Donkey", @"Emu", @"Giraffe", @"Greater Rhea", @"Hippopotamus", @"Horse", @"Koala", @"Lion", @"Llama", @"Manatus", @"Meerkat", @"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear", @"Rhinoceros", @"Seagull", @"Tasmania Devil", @"Whale", @"Whale Shark", @"Wombat"];
以及如何通过首字母分组到nsmutabledictionary。 (取决于数组数据)就像这样。
animals = @{@"B" : @[@"Bear", @"Black Swan", @"Buffalo"],
@"C" : @[@"Camel", @"Cockatoo"],
@"D" : @[@"Dog", @"Donkey"],
@"E" : @[@"Emu"],
@"G" : @[@"Giraffe", @"Greater Rhea"],
@"H" : @[@"Hippopotamus", @"Horse"],
@"K" : @[@"Koala"],
@"L" : @[@"Lion", @"Llama"],
@"M" : @[@"Manatus", @"Meerkat"],
@"P" : @[@"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear"],
@"R" : @[@"Rhinoceros"],
@"S" : @[@"Seagull"],
@"T" : @[@"Tasmania Devil"],
@"W" : @[@"Whale", @"Whale Shark", @"Wombat"]};
谢谢。!!
答案 0 :(得分:1)
自己很容易完成,但无论如何要检查这段代码
NSArray *words = @[@"AS", @"CS", @"AQ", @"CA", @"SA"];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
for (NSString *word in words) {
if (word.length > 0) {
NSString *firstChar = [word substringToIndex:1];
NSMutableArray *contents = dic[firstChar];
if (!contents) {
contents = [NSMutableArray array];
dic[firstChar] = contents;
}
[contents addObject:word];
}
}
答案 1 :(得分:0)
你需要自己做。迭代数组,从项中获取第一个字符,检查它是否存在于字典中,如果存在则添加到数组中,如果不存在则插入新数组。
任何替代方法都将使用提供此功能的第三方库。
答案 2 :(得分:0)
NSArray *animals = @[@"Bear", @"Black Swan", @"Buffalo", @"Camel", @"Cockatoo", @"Dog", @"Donkey", @"Emu", @"Giraffe", @"Greater Rhea", @"Hippopotamus", @"Horse", @"Koala", @"Lion", @"Llama", @"Manatus", @"Meerkat", @"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear", @"Rhinoceros", @"Seagull", @"Tasmania Devil", @"Whale", @"Whale Shark", @"Wombat"];
NSMutableDictionary *animalDict = [NSMutableDictionary dictionary];
for (NSString *animal in animals) {
NSString *firstLetter = [animal substringToIndex:1];
NSMutableArray *letterArray = [animalDict objectForKey:firstLetter];
if (!letterArray) {
letterArray = [NSMutableArray arrayWithObject:animal];
[animalDict setObject:letterArray forKey:firstLetter];
} else {
[letterArray addObject:animal];
[letterArray sortUsingSelector:@selector(caseInsensitiveCompare:)];
}
}
NSLog(@"%@", animalDict);