IOS/Objective-C:按字符串中的单词数对NSStrings的NSArray进行排序



我有一个字符串数组,我想按每个字符串中的单词数进行排序。 但是,我在字典和数组方面很弱,并且难以有效地做到这一点。

一种方法可能是将每个字符串放在包含字符串和单词数的字典中,然后使用 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]];

我不清楚将单词和单词数添加到字典中的代码。即使我知道代码,这似乎也非常麻烦。

有没有办法按每个字符串中的单词数快速对字符串数组进行排序?

提前感谢您的任何建议。

您应该首先使用字数统计方法扩展NSString

@interface NSString(WordCount)
- (NSUInteger)wordCount;
@end
@implementation NSString(WordCount)
- (NSUInteger)wordCount
{
// There are several ways to do this. Pick up your own on SO or another place of the internet. I took this one:
__block NSUInteger count = 0;
[self enumerateSubstringsInRange:NSMakeRange(0, string.length)
options:NSStringEnumerationByWords
usingBlock:
^(NSString *character, NSRange substringRange, NSRange enclosingRange, BOOL *stop) 
{
count++;
}];
return count;
}

这有优点:

  • 您可以将此方法用于其他原因。
  • 字数统计是字符串的属性,因此该方法应该是类NSString的成员。

现在您可以简单地使用排序描述符:

NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"wordCount" ascending:YES];
NSArray *sortedStrings = [myWordGroups sortedArrayUsingDescriptors:@[sorter]];

我有一个字符串数组,我想按每个字符串中的单词数进行排序

首先编写一个实用程序方法,该方法接受一个字符串并返回其中的单词数(无论这对您意味着什么(。然后调用sortedArrayUsingComparator:以根据在每个元素上调用实用程序方法的结果对字符串数组进行排序。

一个简单的实现(假设句子中的单词用空格分隔(可能如下所示:

// create a comparator
NSComparisonResult (^comparator)(NSString *, NSString *) = ^ (NSString *firstString, NSString *secondString){
NSUInteger numberOfWordsInFirstString = [firstString componentsSeparatedByString:@" "].count;
NSUInteger numberOfWordsInSecondString = [secondString componentsSeparatedByString:@" "].count;
if (numberOfWordsInFirstString > numberOfWordsInSecondString) {
return NSOrderedDescending;
} else if (numberOfWordsInFirstString < numberOfWordsInSecondString) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
};
NSArray *strings = @[@"a word", @"even more words", @"a lot of words", @"more words", @"i can't even count the words"];
// use the comparator to sort your array of strings
NSArray *stringsSortedByNumberOfWords = [strings sortedArrayUsingComparator:comparator];
NSLog(@"%@", stringsSortedByNumberOfWords);
// results in:
// "a word",
// "more words",
// "even more words",
// "a lot of words",
// "i can't even count the words"

这是 Objective-C 代码

NSArray *myWordGroups = @[@"three",@"one two three",@"one two"];
NSArray *sortedStrings = [myWordGroups sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self.length" ascending:YES]]];
// => Sorted Array : @[@"three", @"one two", @"one two three"]

最新更新