【发布时间】:2018-10-03 21:01:15
【问题描述】:
我有一个字符串数组,我想按每个字符串中的单词数对其进行排序。但是,我在字典和数组方面很弱,并且无法有效地做到这一点。
一种方法可能是将每个字符串放入包含字符串和单词数的字典中,然后使用 NSSortDescriptor 按单词数对字典进行排序。
类似:
NSArray *myWordGroups = @[@"three",@"one two three",@"one two"];
NSMutableArray *arrayOfDicts=[NSMutableArray new];
for (i=0;i<[myWordGroups count];i++) {
long numWords = [myWordGroups[i] count];
//insert word and number into dictionary and add dictionary to new array
}
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"numWords"
ascending:NO];
NSArray *sortedArray = [myWords sortedArrayUsingDescriptors:@[sortDescriptor]];
我不清楚将单词和单词数添加到字典中的代码。即使我知道这些代码,这似乎也非常麻烦。
有没有办法根据每个字符串中的单词数快速对字符串数组进行排序?
提前感谢您的任何建议。
【问题讨论】:
-
您可以按此处所述获取字数:stackoverflow.com/questions/6171422/…
标签: ios objective-c nsarray