从两个阵列中获取匹配的字符串

时间:2011-08-25 17:40:14

标签: objective-c nsstring nsarray

如何将NSArray中匹配的字符串与NSMutableArray中的一个索引差异保存?

例如,有三个“苹果”,四个“菠萝”,六个“香蕉”,两个“可可”,其余的单词在nsarray中没有重复,我想知道是否有nsarray至少有两个相同的词。如果是的话,我想在nsmutablearray中保存“apple”,“pineapple”,“banana”和“cocoa”。如果有其他类似的话,我也想将它们添加到namutablearray中。

我的代码(仍然无法正常工作);

NSArray *noWords = [[NSArray alloc] initWithArray:
                          [[NSString stringWithContentsOfFile:[[NSBundle mainBundle] 
                             pathForResource:@"words" ofType:@"txt"]                                               
                             encoding:NSUTF8StringEncoding error:NULL] 
                            componentsSeparatedByString:@"\n"]];

NSUInteger scount = [noWords count];
int ii = 0;
NSString *stringline;
for (ii; ii < scount; ii++)
{
    stringline = [noWords objectAtIndex:ii];
    NSLog(@"stringline : %@ ", stringline);
}
int i = 1;
NSString *line;
for (i ; i < 10; i++)
{
    line = [noWords objectAtIndex:i];
    NSLog (@"line : %@ ", line);

    NSMutableArray *douwords = [NSMutableArray array];

    if ([stringline isEqualToString:line])
    {
        NSString *newword;
        for (newword in douwords)
        {
            [douwords addObject:newword]; 
            NSLog (@"detected! %@ ", douwords);
        }
    }
}

3 个答案:

答案 0 :(得分:3)

以下是使用两套的解决方案:

- (NSArray *)getDuplicates:(NSArray *)words
{
    NSMutableSet *dups = [NSMutableSet set],
                 *seen = [NSMutableSet set];

    for (NSString *word in words) {
        if ([seen containsObject:word]) {
            [dups addObject:word];
        }
        [seen addObject:word];
    }

    return [dups allObjects];
}

假设NSSet在幕后使用哈希表(我打赌它会这样做),这将比之前建议的O(n ^ 2)解决方案更快。

答案 1 :(得分:2)

这是我头脑中的一些东西:

NSMutableSet* duplicates = [NSMutableSet set];
NSArray* words = [NSArray arrayWithObjects:@"Apple", @"Apple", @"Orange", @"Apple", @"Orange", @"Pear", nil];
[words enumerateObjectsUsingBlock:^(NSString* str, NSUInteger idx, BOOL *stop) {
    for (int i = idx + 1; i < words.count; i++) {
        if ([str isEqualToString:[words objectAtIndex:i]]) {
            [duplicates addObject:str];
            break;
        }
    }
}];
NSLog(@"Dups: %@", [duplicates allObjects]); // Prints "Apple" and "Orange"

与NSArray相比,使用NSSet可确保不会多次添加字符串。显然,可以进行优化,但这应该是一个很好的起点。

答案 2 :(得分:1)

我假设您想要计算数组中单词的外观并输出计数多于一的单词。一个基本而冗长的方法是:

// Make an array of words - some duplicates
NSArray *wordList = [[NSArray alloc] initWithObjects:
                    @"Apple", @"Banana", @"Pencil",
                    @"Steve Jobs", @"Kandahar",
                    @"Apple", @"Banana", @"Apple",
                    @"Pear", @"Pear", nil];

// Make an mutable dictionary - the key will be a word from the list
// and the value will be a number representing the number of times the
// word appears in the original array. It starts off empty.
NSMutableDictionary *wordCount = [[NSMutableDictionary alloc] init];

// In turn, take each word in the word list...
for (NSString *s in wordList) {

    int count = 1;

    // If the word is already in the dictionary
    if([wordCount objectForKey:s]) {

        // Increse the count by one
        count = [[wordCount objectForKey:s] intValue] + 1;

    }

    // Save the word count in the dictionary
    [wordCount setObject:[NSNumber numberWithInt:count] forKey:s];
}

// For each word...
for (NSString *s in [wordCount keysOfEntriesPassingTest:
                     ^(id key, id obj, BOOL *stop) {
                         if ([obj intValue] > 1) return YES; else return NO;
                     }]) {

    // print the word and the final count
    NSLog(@"%2d %@", [[wordCount objectForKey:s] intValue], s);

}

输出结果为:

3 Apple
2 Pear
2 Banana