Objective-C: How to find the most common string in an array?

后端 未结 3 1529
礼貌的吻别
礼貌的吻别 2021-01-21 08:02

I have an array of strings from an online database that I trying to determine the most commonly used word. The values inside the arrays will vary but I want to check the most co

3条回答
  •  無奈伤痛
    2021-01-21 08:42

    Simplest way is probably NSCountedSet:

    NSCountedSet* stringSet = [[NSCountedSet alloc] initWithArray:strings];
    NSString* mostCommon = nil;
    NSUInteger highestCount = 0;
    
    for(NSString* string in stringSet) {
        NSUInteger count = [stringSet countForObject:string];
        if(count > highestCount) {
            highestCount = count;
            mostCommon = string;
        }
    }
    

提交回复
热议问题