On Sep 20, 2014, at 11:13 AM, 2551 <2551p...@gmail.com> wrote: > For example: > > NSString *mary = @"mary had a little lamb, a little lamb she had"; > NSString *scary = @"mary had a little lamb, a little naughty fella of a > lamb she had for sure"; > NSString *isDifferent = [self getDifference:mary and: scary]; > NSLog(@"%@", isDifferent); > > The method I posted below produces the difference that I want ("naughty fella > of a for sure"). But I want to know if there's a more orthodox and robust > solution. >>>
I would use an NSOrderedSet and NSCharacterSet for robustness, e.g.: NSMutableCharacterSet *separatorSet = [NSMutableCharacterSet punctuationCharacterSet]; [separatorSet formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSMutableOrderedSet *maryWords = [NSMutableOrderedSet orderedSetWithArray:[mary componentsSeparatedByCharactersInSet:separatorSet]]; NSMutableOrderedSet *scaryWords = [NSMutableOrderedSet orderedSetWithArray:[scary componentsSeparatedByCharactersInSet:separatorSet]]; BOOL maryLonger = [maryWords count] > [scaryWords count]; [(maryLonger ? maryWords : scaryWords) minusOrderedSet:(maryLonger ? scaryWords : maryWords)]; NSLog(@"%@", (maryLonger ? maryWords : scaryWords)); Though this wouldn't account for order or duplicates, but neither would your implementation. >> >>> -(NSString *)getDifference: (NSString *)aString and:(NSString >>> *)anotherString { >>> int i = aString.length; >>> int j = anotherString.length; >>> NSString *result, *longest, *shortest; >>> >>> if (i == j) { >>> result = @""; >>> return result; >>> } >>> >>> if (i > j) { >>> longest = aString; >>> shortest = anotherString; >>> } else { >>> longest = anotherString; >>> shortest = aString; >>> } >>> >>> NSArray *fa = [longest componentsSeparatedByString: @" " ]; >>> NSArray *sa = [shortest componentsSeparatedByString: @" "]; >>> NSMutableArray *remainder = [NSMutableArray arrayWithArray:fa]; >>> [remainder removeObjectsInArray:sa]; >>> result = [remainder componentsJoinedByString:@" "]; >>> return result; >>> >>> } Keary Suska Esoteritech, Inc. "Demystifying technology for your home or business" _______________________________________________ Cocoa-dev mailing list (Cocoa-dev@lists.apple.com) Please do not post admin requests or moderator comments to the list. Contact the moderators at cocoa-dev-admins(at)lists.apple.com Help/Unsubscribe/Update your Subscription: https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com This email sent to arch...@mail-archive.com