前の質問に対するこの回答と同様に続行できます。
NSString *string1 = @"optimusprime";
NSString *string2 = @"dejathoras";
// Combine strings:
NSString *combined = [string1 stringByAppendingString:string2];
// Now remove duplicate characters:
NSMutableString *result = [combined mutableCopy];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
// Check if current character already occurred at an earlier location:
NSRange previousRange = [result rangeOfString:substring
options:0
range:NSMakeRange(0, substringRange.location)];
if (previousRange.location != NSNotFound) {
[result deleteCharactersInRange:substringRange];
}
}];
NSLog(@"%@", result);
出力:optimusredjah
編集:上記のソリューションは、あまりうまくスケーリングしません。@wafの回答で提案されているように、重複した文字を辞書に保存するか、セットに保存する方がおそらく良いでしょう:
NSMutableString *result = [combined mutableCopy];
NSMutableSet *chars = [NSMutableSet set];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if ([chars containsObject:substring]) {
[result deleteCharactersInRange:substringRange];
} else {
[chars addObject:substring];
}
}];