我有一个字符串,例如@"012"
,我有另一个字符串@"02"
。如何在iPhone Objective-C中提取2个字符串的差异。我只需要从第一个字符串中删除第二个字符串中字符的存在。答案是“1”。
答案 0 :(得分:12)
更短:
NSString* s1 = @"012";
NSString* s2 = @"02";
NSCharacterSet * set = [NSCharacterSet characterSetWithCharactersInString:s2];
NSString * final = [[s1 componentsSeparatedByCharactersInSet:set] componentsJoinedByString:@""];
NSLog(@"Final: %@", final);
这会保留原始字符串中字符的顺序。
答案 1 :(得分:1)
你可以做这样的事情;
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];
免责声明:我在浏览器中输入了此内容,但尚未对此进行测试。
答案 2 :(得分:0)
您正在尝试进行设置操作,因此请使用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);
}
答案 3 :(得分:0)
我只是使用“componentsSeparatedByString”
NSString *s1 = @"abc";
NSString *s2 = @"abcdef";
//s2 - s1
NSString * final = [[s2 componentsSeparatedByString:s1] componentsJoinedByString:@""];