Subtracting 2 strings
I have a string say for example @"012"
and开发者_StackOverflow中文版 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".
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.
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.
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);
}
I simply used "componentsSeparatedByString"
NSString *s1 = @"abc";
NSString *s2 = @"abcdef";
//s2 - s1
NSString * final = [[s2 componentsSeparatedByString:s1] componentsJoinedByString:@""];
精彩评论