I have a string say for example @"012"
and I have another string @"02"
. How can I extract the difference of the 2 strings in iPhone Objective-C. I just need to remove the existence of the characters in the 2nd string from the first string.The answer would be "1".
views:
148answers:
3
A:
You're trying to do a set operation, so use sets.
{
NSString* s1 = @"012";
NSString* s2 = @"02";
NSMutableSet* set1 = [NSMutableSet set];
NSMutableSet* set2 = [NSMutableSet set];
for(NSUInteger i = 0; i < [s1 length]; ++i)
{
[set1 addObject:[s1 substringWithRange:NSMakeRange(i, 1)]];
}
for(NSUInteger i = 0; i < [s2 length]; ++i)
{
[set2 addObject:[s2 substringWithRange:NSMakeRange(i, 1)]];
}
[set1 minusSet:set2];
NSLog(@"set1: %@", set1);
// To get a single NSString back from the set:
NSMutableString* result = [NSMutableString string];
for(NSString* piece in set1)
{
[result appendString:piece];
}
NSLog(@"result: %@", result);
}
nall
2009-11-25 04:58:13
how can i retrieve the results in nsset as nsstring ??
Bapu
2009-11-25 05:14:14
Updated to do this
nall
2009-11-25 05:16:31
I think the characters in the resulting string are not necessarily in the same order, though. Might be a problem or not, I don't know. Testing with "012" and "02" won't reveal this.
Thomas Müller
2009-11-25 05:32:48
+1
A:
You could do something like this;
NSString *s1 = @"012";
NSString *s2 = @"02";
NSCharacterSet *charactersToRemove;
charactersToRemove = [NSCharacterSet characterSetWithCharactersInString:s2];
NSMutableString *result = [NSMutableString stringWithCapacity:[s1 length]];
for (NSUInteger i = 0; i < [s1 length]; i++) {
unichar c = [s1 characterAtIndex:i];
if (![charactersToRemove characterIsMember:c]) {
[result appendFormat:@"%C", c];
}
}
// if memory is an issue:
result = [[result copy] autorelease];
Disclaimer: I typed this into the browser, and haven't tested any of this.
Thomas Müller
2009-11-25 05:42:02
+7
A:
Even shorter:
NSString* s1 = @"012";
NSString* s2 = @"02";
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:s2];
NSString * final = [[s1 componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
NSLog(@"Final: %@", final);
This preserves the order of the characters in the original string.
Dave DeLong
2009-11-25 05:47:37