将数组sorting为字典

我有许多string的数组。 我不想将它们sorting成字典,所有开始相同字母的string进入一个数组,然后数组变成一个键的值; 关键是字母数组中所有单词开始的字母。

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

你可以通过以下步骤达到你想要的效果:

  1. 创build一个空的,但可变的字典。
  2. 获取第一个字符。
  3. 如果该字符的键不存在,请创build它。
  4. 将该单词添加到键的值(应该是一个NSMutableArray)。
  5. 对所有键重复步骤#2。

这是这些步骤的Objective-C代码。 请注意,我假设你想要的键不区分大小写

 // create our dummy dataset NSArray * wordArray = [NSArray arrayWithObjects:@"Apple", @"Pickle", @"Monkey", @"Taco", @"arsenal", @"punch", @"twitch", @"mushy", nil]; // setup a dictionary NSMutableDictionary * wordDictionary = [[NSMutableDictionary alloc] init]; for (NSString * word in wordArray) { // remove uppercaseString if you wish to keys case sensitive. NSString * letter = [[word substringWithRange:NSMakeRange(0, 1)] uppercaseString]; NSMutableArray * array = [wordDictionary objectForKey:letter]; if (!array) { // the key doesn't exist, so we will create it. [wordDictionary setObject:(array = [NSMutableArray array]) forKey:letter]; } [array addObject:word]; } NSLog(@"Word dictionary: %@", wordDictionary); 

看看这个主题,他们解决了几乎和你一样的问题 – 过滤NSArray在Objective-C中的新NSArray让我知道如果它不帮助,所以我会再写一个代码示例。

用这个按字母顺序排列数组的内容,进一步devise到需求

[keywordListArr sortUsingSelector:@selector(localizedCaseInsensitiveCompare :)];

我刚写了这个样本。 它看起来很简单,做你所需要的。

 NSArray *names = [NSArray arrayWithObjects:@"Anna", @"Antony", @"Jack", @"John", @"Nikita", @"Mark", @"Matthew", nil]; NSString *alphabet = @"ABCDEFGHIJKLMNOPQRSTUWXYZ"; NSMutableDictionary *sortedNames = [NSMutableDictionary dictionary]; for(int characterIndex = 0; characterIndex < 25; characterIndex++) { NSString *alphabetCharacter = [alphabet substringWithRange:NSMakeRange(characterIndex, 1)]; NSArray *filteredNames = [names filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF BEGINSWITH[C] %@", alphabetCharacter]]; [sortedNames setObject:filteredNames forKey:alphabetCharacter]; } //Just for testing purposes let's take a look into our sorted data for(NSString *key in sortedNames) { for(NSString *value in [sortedNames valueForKey:key]) { NSLog(@"%@:%@", key, value); } }