开发者

Get matched string from two NSArrays

开发者 https://www.devze.com 2023-03-31 07:19 出处:网络
How can I save the string that match from one NSArray with one index difference in NSMutableArray? For example, there are three \"apple\", four \"pineapple\", six \"banana\", two \"cocoa\" and the re

How can I save the string that match from one NSArray with one index difference in NSMutableArray?

For example, there are three "apple", four "pineapple", six "banana", two "cocoa" and the rest of words dont have duplicate(s) in the nsarray, i would like to know if the nsarray ha开发者_开发问答s at least two same words. If yes, I would like to save "apple", "pineapple, "banana" and "cocoa" once in nsmutablearray. If there are other alike words, I would like to add them to namutablearray too.

My code (which still doesn't work properly);

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);
        }
    }
}


Here's a solution using two sets:

- (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];
}

Assuming NSSet uses hash tables behind the scenes (which I'm betting it does), this is going to be faster than the previously suggested O(n^2) solution.


Here's something off the top of my head:

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"

The use of an NSSet, as opposed to an NSArray, ensures strings are not added more than once. Obviously, there are optimizations that could be done, but it should be a good starting point.


I assume that you want to count appearances of words in your array and output those with a count of more than one. A basic and verbose way to do that would be:

// 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);

}

The output would be:

3 Apple
2 Pear
2 Banana
0

精彩评论

暂无评论...
验证码 换一张
取 消