Re: return string that is the difference between two other strings
Re: return string that is the difference between two other strings
- Subject: Re: return string that is the difference between two other strings
- From: Keary Suska <email@hidden>
- Date: Sat, 20 Sep 2014 11:41:48 -0600
On Sep 20, 2014, at 11:13 AM, 2551 <email@hidden> 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 (email@hidden)
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:
This email sent to email@hidden