【问题标题】:IOS/Objective-C: Sort NSArray of NSStrings by number of words in stringIOS/Objective-C:按字符串中的单词数对 NSStrings 的 NSArray 进行排序
【发布时间】: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]];

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

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

提前感谢您的任何建议。

【问题讨论】:

标签: ios objective-c nsarray


【解决方案1】:

你应该先用字数方法扩展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]];

【讨论】:

  • 代码编译但尝试访问 wordCount(或 WordCount)会引发无法识别的选择器异常
  • 让它与 Koen 提供的链接中的一种字数统计方法一起工作。问题是因为 wordCount 是 NSString 上的一个方法,它需要引用 self 作为字符串,而不是 String 作为参数。在 Amin 的方法中,我认为你也会变成自己。
  • 哦,是的,……我改了。
【解决方案2】:

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

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

【讨论】:

  • 你把代码统计单词并在比较器块中进行比较?
【解决方案3】:

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

// 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"

【讨论】:

    【解决方案4】:

    这是 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"]
    

    【讨论】:

    • 所需的排序是字数,而不是字符串长度。
    猜你喜欢
    • 2012-01-26
    • 2014-07-30
    • 2011-08-14
    • 1970-01-01
    • 2016-08-31
    • 2014-02-22
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    相关资源
    最近更新 更多